def generateImage(word):
    saveToXML(word)

    print("Waiting for Unity to generate image...")

    hwnd = 0
    hwnd = win32gui.FindWindow(None, "ToonRendering")
    if hwnd == 0:

        def callback(h, extra):
            if "ToonRendering" in win32gui.GetWindowText(h):
                extra.append(h)
            return True

        extra = []
        win32gui.EnumWindows(callback, extra)
        if extra: hwnd = extra[0]
    if hwnd == 0:
        print(
            "Unity window 'ToonRendering' not found. Please ensure Unity is running and switch to it manually."
        )
    win32gui.SetForegroundWindow(hwnd)

    global genimg

    while True:
        if os.path.isfile(genimg + str(word['idnumber']) + ".png"):
            break
    imageString = tf.read_file(genimg + str(word['idnumber']) + ".png")

    hwnd = 0
    hwnd = win32gui.FindWindow(None, "Art Style Replicator")
    if hwnd == 0:

        def callback(h, extra):
            if "Art Style Replicator" in win32gui.GetWindowText(h):
                extra.append(h)
            return True

        extra = []
        win32gui.EnumWindows(callback, extra)
        if extra: hwnd = extra[0]
    if hwnd == 0:
        print("Python window 'Art Style Replicator' not found.")
    win32gui.SetForegroundWindow(hwnd)

    imageString = tf.image.decode_png(imageString, dtype=tf.uint16)
    imageString = tf.image.convert_image_dtype(imageString, tf.float32)

    ############### Convert word['image'] to tensor4 ################
    global train_data_width
    global train_data_height
    word['image'] = tf.reshape(imageString,
                               [1, train_data_height, train_data_width, 3])

    print("Retrieved generated image")

    return word['image']
Пример #2
0
    def resetWindow(self):
        def isMinimized(handle):
            return win32gui.IsIconic(handle)

        def SetAsForegroundWindow(window, restore=False):
            shell = win32com.client.Dispatch("WScript.Shell")
            shell.SendKeys(
                '%'
            )  #msg obrigatoria antes de qualquer mudanca na gui do windows
            win32gui.SetForegroundWindow(window)
            if restore:
                win32gui.ShowWindow(
                    window, win32con.SW_RESTORE
                )  #https://msdn.microsoft.com/pt-br/library/windows/desktop/ms633548(v=vs.85).aspx

        def getForegroundWindow():
            return win32gui.GetForegroundWindow()

        print("resetWindow foi chamado")
        wtitle = self.driver.title + " - Google Chrome"
        window = win32gui.FindWindow(None, wtitle)
        if isMinimized(window):
            wInicial = getForegroundWindow()
            SetAsForegroundWindow(window, True)
            SetAsForegroundWindow(wInicial, False)
Пример #3
0
def close_window_by_name(name):
    try:
        target_hwnd = win32gui.FindWindow(None, name)
        tid, pid = win32process.GetWindowThreadProcessId(target_hwnd)
        os.kill(pid, signal.SIGTERM)
    except:
        pass
Пример #4
0
    def _setRoot(self, init_line):

        root = tk.Tk()
        root.title(init_line)

        # configure the overlay widget, aka the master widget of the line we have created
        root.overrideredirect(
            True
        )  # this prevents the override from behaving like a regular window
        root.geometry(f'+{self.position["X"]}+{self.position["Y"]}'
                      )  # this sets overlay's initial position
        root.minsize(
            500, 20)  # set minimum widget size to max of what it will ever be
        root.configure(
            bg=self.colors['background'])  # set the BG colour of the widget
        root.wm_attributes(
            '-topmost',
            True)  # make sure the overlay widget stays on top of other windows
        root.wm_attributes(
            '-alpha',
            self.opacity)  # set opacity to make the widget semi-transparent

        root.update()

        # set the window to allow clicking events to go through
        window = win32gui.FindWindow(None,
                                     init_line)  # find our window to edit it
        lExStyle = win32gui.GetWindowLong(window, win32con.GWL_EXSTYLE)
        lExStyle |= win32con.WS_EX_TRANSPARENT | win32con.WS_EX_LAYERED
        win32gui.SetWindowLong(window, win32con.GWL_EXSTYLE, lExStyle)

        return root
Пример #5
0
    def click(self, x, y):
        if self.click_by_mouse:
            window_title = self._getWindowTitle()
            try:
                hwin = win32gui.FindWindow('LDPlayerMainFrame', window_title)
                self._subhwin = None

                def winfun(hwnd, lparam):
                    subtitle = win32gui.GetWindowText(hwnd)
                    if subtitle == 'TheRender':
                        self._subhwin = hwnd

                win32gui.EnumChildWindows(hwin, winfun, None)
                ret = win32gui.GetWindowRect(self._subhwin)
                height = ret[3] - ret[1]
                width = ret[2] - ret[0]
                tx = int(x * width / constants.BASE_WIDTH)
                ty = int(y * height / constants.BASE_HEIGHT)
                positon = win32api.MAKELONG(tx, ty)
                win32api.SendMessage(self._subhwin, win32con.WM_LBUTTONDOWN,
                                     win32con.MK_LBUTTON, positon)
                win32api.SendMessage(self._subhwin, win32con.WM_LBUTTONUP,
                                     win32con.MK_LBUTTON, positon)
            except Exception as e:
                print(f"fallback adb click:{e}")
                super().click(x, y)
        else:
            super().click(x, y)
Пример #6
0
 def switch_to_terminal_window(self):
     if win32gui.GetForegroundWindow() == self.script.window:
         window2 = win32gui.FindWindow(
             "ConsoleWindowClass",
             "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe"
         )
         self.script.focus_on_window(window2)
         time.sleep(1)
def getFrame():
    hwnd = win32gui.FindWindow(None, r'Grand Theft Auto V')
    win32gui.SetForegroundWindow(hwnd)
    dimensions = win32gui.GetWindowRect(hwnd)
    pressKey(DIK_E)
    pressKey(DIK_PAGE_UP)
    sleep(1)
    image = ImageGrab.grab(dimensions)
    return image
Пример #8
0
    def SetAsForegroundWindow(self, name):
        # 获取后台窗口的句柄,注意后台窗口不能最小化
        hWnd = win32gui.FindWindow(None, name)  # 参数1为类名,参数2为标题

        # 通过pywin32模块下的SetForegroundWindow函数调用时,会出现error: (0, 'SetForegroundWindow', 'No error message is available')
        # 报错,后经网上查询确认,为pywin32模块下的一个小bug,在该函数调用前,需要先发送一个其他键给屏幕,如ALT键 。
        self.shell.SendKeys('%')
        print(hWnd)
        win32gui.SetForegroundWindow(hWnd)
Пример #9
0
 def __init__(self):
     self.k = PyKeyboard()  # get pykeyboard
     self.software = u'网上股票交易系统5.0'
     self.hWndChildList = 0
     self.para_hld = win32gui.FindWindow(None, self.software)
     if self.IsWindow():
         self.hWndChildList = self.demo_child_windows(self.para_hld)  # get hld
         attr = self.show_window_attr(self.para_hld)
         win32api.SetCursorPos([attr['post'][0], attr['post'][1]])  # Mover to post(x,y)
def on_press(key):
    if key == Key.end:
        global startScript, inputBet, inputColor
        if inputBet != None and inputColor != None:
            startScript = not startScript
            if startScript:
                hwnd = win32gui.FindWindow(None, r'Grand Theft Auto V')
                win32gui.SetForegroundWindow(hwnd)
                win32gui.MoveWindow(hwnd, 0, 0, 1336, 797, True)
            print("\n\nScript status: ", startScript, "\n\n")
Пример #11
0
    def __init__(self, sender_name, classname, titlename):
        self.cur_hwnd = win32gui.GetForegroundWindow()

        self.sender_name = sender_name
        self.classname = classname
        self.titlename = titlename
        self.con_hwnd = win32gui.FindWindow(classname, titlename)
        if not self.con_hwnd:
            print('can not find window, exit.')
            exit(0)
        self.lock = Lock()
Пример #12
0
 def screenshot(self):
     if not self.dimensions:
         hwnd = win32gui.FindWindow(None, r'Euro Truck Simulator 2')
         win32gui.SetForegroundWindow(hwnd)
         dimensions = win32gui.GetWindowRect(hwnd)
         dimensions = list(dimensions)
         dimensions[0] += 10
         dimensions[1] += 30
         dimensions[2] -= 10
         dimensions[3] -= 10
         self.dimensions = (dimensions)
     return ImageGrab.grab(bbox=self.dimensions)
Пример #13
0
    def __init_window(self):
        # 画面サイズの取得
        screen_x, screen_y = pyautogui.size()

        # win32guiを使ってウインドウタイトルを探す
        # Windowのハンドル取得('クラス名','タイトルの一部')で検索クラスがわからなかったらNoneにする
        parent_handle = win32gui.FindWindow(None, "Mine2000")

        # ハンドルIDが取れなかったら、mine2000を起動する
        if parent_handle == 0:
            cmd = 'C:\Program Files (x86)\mine2000 project\mine2000 ver2.2.1\mine2000.exe'
            subprocess.Popen(cmd, shell=True)
            time.sleep(1)
            parent_handle = win32gui.FindWindow(None, "Mine2000")

        if parent_handle == 0:
            sys.exit()

        # ハンドルが取れたら、ウインドウの左上と右下の座標取得と画面のアクティブ化
        if parent_handle > 0:
            w0, h0, w1, h1 = win32gui.GetWindowRect(parent_handle)
            apw_x = w1 - w0
            apw_y = h1 - h0

            # ウィンドウをアクティブに持ってくる
            win32gui.SetForegroundWindow(parent_handle)
            time.sleep(0.5)

            # ウィンドウを画面中央に持ってくる
            x_pos = int((screen_x - apw_x) / 2)
            y_pos = int((screen_y - apw_y) / 2)
            win32gui.MoveWindow(parent_handle, x_pos, y_pos, apw_x, apw_y,
                                True)

            # スクリーンショット用に座標を調整する
            return (w0 + 4, h0 + 79, w1 - 4, h1)

        raise Exception
def abre_arquivo(dir):
    # Loop até que a caixa de diálogo Open seja exibida
    hdlg = 0
    while hdlg == 0:
        hdlg = win32gui.FindWindow(None, "Abrir")

    # Define o nome do arquivo e pressione a tecla Enter
    hwnd = win32gui.FindWindowEx(hdlg, 0, "ComboBoxEx32", None)
    hwnd = win32gui.FindWindowEx(hwnd, 0, "ComboBox", None)
    hwnd = win32gui.FindWindowEx(hwnd, 0, "Edit", None)
    win32gui.SendMessage(hwnd, win32con.WM_SETTEXT, None, dir)
    # Pressiona o botão Salvar
    hwnd = win32gui.FindWindowEx(hdlg, 0, "Button", "&Abrir")
    win32gui.SendMessage(hwnd, win32con.BM_CLICK, None, None)
def screenshot(widget):
    path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'screenshot.png')
    if _WIN32:
        targetWindow = win32gui.FindWindow(None, APP_NAME)
        left, top, right, bot = win32gui.GetClientRect(targetWindow)
        w = right - left
        h = bot - top

        hwndDC = win32gui.GetWindowDC(targetWindow)
        mfcDC  = win32ui.CreateDCFromHandle(hwndDC)
        saveDC = mfcDC.CreateCompatibleDC()

        saveBitMap = win32ui.CreateBitmap()
        saveBitMap.CreateCompatibleBitmap(mfcDC, w, h)

        saveDC.SelectObject(saveBitMap)

        result = windll.user32.PrintWindow(targetWindow, saveDC.GetSafeHdc(), 1)

        if result != 0:
            #bmpinfo = saveBitMap.GetInfo()
            bmpstr = saveBitMap.GetBitmapBits(True)

            img = Image.frombuffer('RGB', (w, h),
                bmpstr, 'raw', 'BGRX', 0, 1)

            img.save(path)
        
            #img = img.convert("RGB")
            #data = img.tobytes("raw","RGB")

            #converting to QImage with altering window size causes crash / erroneous images
            #qimg = QImage(data, img.size[0], img.size[1], QImage.Format_RGB888)

            #qimg.save(path)
        else:
            print("Win32 failed, backup qt function used")
            widget.screenCap = widget.screen().grabWindow(widget.long_qdesktop_id,
                        widget.geometry().x(), widget.geometry().y(),
                        widget.width(), widget.height()).save(path, 'png')

        win32gui.DeleteObject(saveBitMap.GetHandle())
        saveDC.DeleteDC()
        mfcDC.DeleteDC()
        win32gui.ReleaseDC(targetWindow, hwndDC)
    else:
        widget.screenCap = widget.screen().grabWindow(widget.long_qdesktop_id,
                                    widget.geometry().x(), widget.geometry().y(),
                                    widget.width(), widget.height()).save(path, 'png')
def send_qq(to_who, msg):
    """发送qq消息
    to_who:qq消息接收人
    msg:需要发送的消息
    """
    # 将消息写到剪贴板
    setText(msg)
    # 获取qq窗口句柄
    qq = win32gui.FindWindow(None, to_who)
    # 投递剪贴板消息到QQ窗体
    win32gui.SendMessage(qq, 258, 22, 2080193)
    win32gui.SendMessage(qq, 770, 0, 0)
    # 模拟按下回车键
    win32gui.SendMessage(qq, win32con.WM_KEYDOWN, win32con.VK_RETURN, 0)
    win32gui.SendMessage(qq, win32con.WM_KEYUP, win32con.VK_RETURN, 0)
Пример #17
0
def get_game_region(title=None):
    if title:
        gamewin = win32gui.FindWindow(None, title)
        if not gamewin:
            raise Exception('window title not found')
        #get the bounding box of the window
        x1, y1, x2, y2 = win32gui.GetWindowRect(gamewin)
        y1 += 30  # get rid of window bar
        h_padding = (y2 - y1) * 0.1
        w_padding = (x2 - x1) * 0.1
        y1 += h_padding
        y2 -= h_padding
        x1 += w_padding
        x2 -= w_padding
        return (x1, y1, (x2 - x1 + 1), (y2 - y1 + 1))
    else:
        raise Exception("no window title was given.")
Пример #18
0
    def __init__(self, window_name=None):
        if window_name is None:
            self.hwnd = win32gui.GetDesktopWindow()
        else:
            self.hwnd = win32gui.FindWindow(None, window_name)
            if not self.hwnd:
                raise Exception('Window not found: {}'.format(window_name))

        window_rect = win32gui.GetWindowRect(self.hwnd)
        self.w = window_rect[2] - window_rect[0]
        self.h = window_rect[3] - window_rect[1]
        border_pixels = 0
        titlebar_pixels = 0
        # self.w = self.w - (border_pixels * 2)
        # self.h = self.h - titlebar_pixels - border_pixels
        # self.cropped_x = border_pixels
        # self.cropped_y = titlebar_pixels
        self.offset_x = window_rect[0] + self.cropped_x
        self.offset_y = window_rect[1] + self.cropped_y
Пример #19
0
def screencap(window_title):
    if window_title:
        hwnd = win32gui.FindWindow(None, window_title)
        if hwnd:
            win32gui.SetForegroundWindow(hwnd)
            x, y, x1, y1 = win32gui.GetClientRect(hwnd)  #get client size
            x, y = win32gui.ClientToScreen(hwnd, (x, y))
            x += 200
            y += 50  #cropping out top part
            x1, y1 = win32gui.ClientToScreen(hwnd, (x1 - x, y1 - y))
            ##            print(x, y, x1, y1)
            x1 -= 400  #cropping out right side
            y1 -= 580  #cropping out bottom part
            im = pyautogui.screenshot(region=(x, y, x1, y1))
            im.save(r'D:\Studies\IDP\SCREENSHOT.png')
        else:
            print('Window not found!')
    else:
        im = pyautogui.screenshot()
        return im
Пример #20
0
def antiafk():

    whnd = win32gui.FindWindow(
        None,
        'World of Warcraft',
    )
    print(whnd)
    time.sleep(2)
    win32gui.SetForegroundWindow(whnd)
    win32gui.SetActiveWindow(whnd)

    keyboard = Controller()

    keyboard.press(Key.esc)
    keyboard.release(Key.esc)
    keyboard.press(Key.space)
    keyboard.release(Key.space)
    time.sleep(1)
    keyboard.press(Key.enter)
    keyboard.release(Key.enter)
    time.sleep(1)
    keyboard.press('/')
    keyboard.release('/')
    time.sleep(1)
    keyboard.press('d')
    keyboard.release('d')
    time.sleep(1)
    keyboard.press('a')
    keyboard.release('a')
    time.sleep(1)
    keyboard.press('n')
    keyboard.release('n')
    time.sleep(1)
    keyboard.press('c')
    keyboard.release('c')
    time.sleep(1)
    keyboard.press('e')
    keyboard.release('e')
    time.sleep(1)
    keyboard.press(Key.enter)
    keyboard.release(Key.enter)
Пример #21
0
 def screenshot(self, output='screen_shot.png'):
     window_title = self._getWindowTitle()
     width, height = constants.BASE_WIDTH, constants.BASE_HEIGHT
     try:
         hwin = win32gui.FindWindow('LDPlayerMainFrame', window_title)
         hwindc = win32gui.GetWindowDC(hwin)
         srcdc = win32ui.CreateDCFromHandle(hwindc)
         memdc = srcdc.CreateCompatibleDC()
         bmp = win32ui.CreateBitmap()
         bmp.CreateCompatibleBitmap(srcdc, width, height)
         memdc.SelectObject(bmp)
         memdc.BitBlt((0, 0), (width, height), srcdc,
                      (0, self._getDnToolbarHeight()), win32con.SRCCOPY)
         signedIntsArray = bmp.GetBitmapBits(True)
         img = np.frombuffer(signedIntsArray, dtype='uint8')
         img.shape = (height, width, 4)
         srcdc.DeleteDC()
         memdc.DeleteDC()
         win32gui.ReleaseDC(hwin, hwindc)
         win32gui.DeleteObject(bmp.GetHandle())
         return img[:, :, :3]
     except:
         return super().screenshot(output=output)
    def captureWindow(self):
        if _WIN32:
            targetWindow = win32gui.FindWindow(None, 'Pokémon Tower Battle')
            left, top, right, bot = win32gui.GetClientRect(targetWindow)
            w = right - left
            h = bot - top

            hwndDC = win32gui.GetWindowDC(targetWindow)
            mfcDC  = win32ui.CreateDCFromHandle(hwndDC)
            saveDC = mfcDC.CreateCompatibleDC()

            saveBitMap = win32ui.CreateBitmap()
            saveBitMap.CreateCompatibleBitmap(mfcDC, w, h)

            saveDC.SelectObject(saveBitMap)

            result = windll.user32.PrintWindow(targetWindow, saveDC.GetSafeHdc(), 1)

            if result != 0:
                bmpstr = saveBitMap.GetBitmapBits(True)

                self.screenCap = Image.frombuffer('RGB', (w, h), bmpstr, 'raw', 'BGRX', 0, 1)
            else:
                #backup function if windows fails
                self.screenCap = self.screen().grabWindow(self.long_qdesktop_id,
                            self.geometry().x(), self.geometry().y(),
                            self.width(), self.height()).toImage()

            win32gui.DeleteObject(saveBitMap.GetHandle())
            saveDC.DeleteDC()
            mfcDC.DeleteDC()
            win32gui.ReleaseDC(targetWindow, hwndDC)
        else:
            #must have screen on top
            self.screenCap = self.screen().grabWindow(self.long_qdesktop_id,
                                       self.geometry().x(), self.geometry().y(),
                                       self.width(), self.height()).toImage()
Пример #23
0
    def find_window(cls, **kwargs):
        """
        查找指定的窗口

        @param {kwargs} - 具体实现类的扩展参数
            muti_search {bool} - 是否返回所有匹配结果,默认为False,仅返回第一个结果
            handle {int} - 窗口句柄, 如果指定该参数则直接获取该句柄的窗口, 不处理其他参数
            top_level_only {bool} - 仅限顶级元素(默认值=True), 如果指定该参数则仅使用class_name、name检索顶层窗口, 不处理其他参数
            class_name {str} - 窗口的类名(可通过spy++获取到)
            name {str} - 窗口标题
            depth {int} - 最大搜索深度(数量,默认值5000)
            class_name_re {str} - 类与此正则表达式匹配的元素
            name_re {str} - 文本与此正则表达式匹配的元素
            parent {int} - 父窗口对象(句柄或WindowControlSpec对象)
            process {int} - 窗口所在的应用进程对象(进程ID)
            visible_only {bool} - 仅可见元素 (默认值=False)
            enabled_only {bool} - 仅启用元素 (默认值=False)
            active_only {bool} - 仅限活动元素(默认= False)

        @returns {WindowControlSpec|list} - 返回窗口对象,如果muti_search为True则返回匹配到的窗口数组
        """
        # 默认参数处理
        _kwargs = {
            'muti_search': False,
            'class_name': None,
            'name': None,
            'depth': 5000,
            'top_level_only': True,
            'visible_only': False,
            'enabled_only': False,
            'active_only': False,
        }
        _kwargs.update(kwargs)

        # 直接给了窗口句柄,忽略其他条件
        if 'handle' in _kwargs.keys():
            if _kwargs['muti_search']:
                return [
                    WindowControlSpec(handle=kwargs['handle']),
                ]
            else:
                return WindowControlSpec(handle=kwargs['handle'])

        # 只查找顶级元素
        if _kwargs['top_level_only']:
            _hwnd = win32gui.FindWindow(_kwargs['class_name'], _kwargs['name'])
            if _hwnd == 0:
                if _kwargs['muti_search']:
                    return []
                else:
                    # 找不到窗口抛出异常
                    raise base_control.WindowException('Window not Found')

            if _kwargs['muti_search']:
                return [
                    WindowControlSpec(handle=_hwnd),
                ]
            else:
                return WindowControlSpec(handle=_hwnd)

        # 遍历方式查找
        _enum_para = {
            'search_para': _kwargs,  # 传入的匹配参数
            'current_depth': 0,  # 当前搜索数量
            'windows': []  # 存储返回的对象
        }

        if 'parent' in _kwargs.keys():
            # 有主窗口的情况
            try:
                win32gui.EnumChildWindows(_kwargs['parent'],
                                          cls._enum_windows_call_back,
                                          _enum_para)
            except:
                # 如果回调函数返回False,将会抛出异常,需要屏蔽处理
                pass
        else:
            # 从主窗口开始遍历查找
            try:
                win32gui.EnumWindows(cls._enum_windows_call_back, _enum_para)
            except:
                # 如果回调函数返回False,将会抛出异常,需要屏蔽处理
                pass

            # 再遍历查找子窗口
            if len(_enum_para['windows']) == 0 or _kwargs['muti_search']:
                _enum_para_child = {
                    'search_para': _kwargs,  # 传入的匹配参数
                    'current_depth': _enum_para['current_depth'],  # 当前搜索数量
                    'windows': []  # 存储返回的对象
                }
                for _win in _enum_para['windows']:
                    try:
                        win32gui.EnumChildWindows(_win.handle,
                                                  cls._enum_windows_call_back,
                                                  _enum_para_child)
                        if not _kwargs['muti_search'] and len(
                                _enum_para_child['windows']) > 0:
                            break
                    except:
                        # 如果回调函数返回False,将会抛出异常,需要屏蔽处理
                        pass

                # 合并两个数组
                _enum_para['windows'].extend(_enum_para_child['windows'])

        # 返回结果
        if _kwargs['muti_search']:
            return _enum_para['windows']
        else:
            if len(_enum_para['windows']) > 0:
                return _enum_para['windows'][0]
            else:
                # 找不到窗口抛出异常
                raise base_control.WindowException('Window not Found')
Пример #24
0
    def closApp(self):

        self.para_hld = win32gui.FindWindow(None, self.software)  # get hld by app word

        win32gui.PostMessage(self.para_hld, win32con.WM_CLOSE, 0, 0)
Пример #25
0
 def find_window(self, class_name, window_name=None):
     # FIND A WINDOW BY IT'S SPECIFIC CLASS NAME
     self._handle = win32gui.FindWindow(class_name, window_name)
Пример #26
0
    def save(self, name):
        self.model.save(name)


##IMAGE CAPTURE AND GAME RESET###


def process_img(original_img):
    process_img = cv2.cvtColor(original_img, cv2.COLOR_BGR2GRAY)
    process_img = cv2.Canny(process_img, threshold1=200, threshold2=300)
    return process_img


names = win32gui.GetWindowText(win32gui.GetForegroundWindow())
hwnd = win32gui.FindWindow(None, r'chrome://dino/ - Google Chrome')
win32gui.SetForegroundWindow(hwnd)
dimensions = win32gui.GetWindowRect(hwnd)
x1, y1, x2, y2 = dimensions
state_size = 50 * 13
action_size = 3
agent = DQNAgent(state_size, action_size)
for e in range(n_episodes):
    reward = 0
    ##Prep for Agent###
    # time1 = time.time()
    done = False
    while (done == False):
        im_L = ImageGrab.grab(
            (x1 + 20, y1 + 250, x2 * 2.8 / 3, y2 - (y2) * 7.17 / 12))
        next_state = []
Пример #27
0
 def open(self):
     self.__app_instance = subprocess.Popen(self.__snake_exec_path)
     time.sleep(5)
     self.__hwnd_main = win32gui.FindWindow(None, "Snake")
import ctypes

kernel32 = ctypes.windll.LoadLibrary(r"C:/Windows/System32/kernel32.dll")


def GetAddress(handle, BaseAddress=0x00197f1c, offset=[0x5578]):
    value = ctypes.c_long()
    kernel32.ReadProcessMemory(int(handle), BaseAddress, ctypes.byref(value),
                               4, None)
    for i in range(len(offset) - 1):
        kernel32.ReadProcessMemory(int(handle), value.value + offset[i],
                                   ctypes.byref(value), 4, None)
    return value.value + offset[len(offset) - 1]


hwnd = win32gui.FindWindow("MainWindow", "Plants vs. Zombies")
pid = win32process.GetWindowThreadProcessId(hwnd)[1]
handle = win32api.OpenProcess(0x1F0FFF, False, pid)

currentSun = ctypes.c_long()
changeSun = ctypes.c_long()

while True:
    address = GetAddress(handle)
    kernel32.ReadProcessMemory(int(handle), address, ctypes.byref(currentSun),
                               4, None)
    print("{}:{}".format("当前阳光", currentSun.value))
    changeSun.value = int(input("要修改成多少:"))
    kernel32.WriteProcessMemory(int(handle), address, ctypes.byref(changeSun),
                                4, None)
Пример #29
0
import numpy
import traceback
from tkinter import *


def imageThere(images):
    img = d.get_latest_frame()
    img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    for i in images:
        res = cv2.matchTemplate(img_gray, i[0], cv2.TM_CCOEFF_NORMED)
        min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
        if max_val >= 0.8:
            return i[1]
    return None

HWND = win32gui.FindWindow(None, 'Fable 3')
win32gui.SetForegroundWindow(HWND)

x, y, x1, y1 = win32gui.GetClientRect(HWND)
x, y = win32gui.ClientToScreen(HWND, (x, y))
x1, y1 = win32gui.ClientToScreen(HWND, (x1 - x, y1 - y))
RAW_REGION = (x, y, x1, y1)
REGION = (x, int(y1*0.7), x1, y1)

print("""
        ----------------------------------------------------
        beep beep... showing image of what will be searched.
            """)

window = Tk()
window.overrideredirect(True)
Пример #30
0
def loadSettings(self: AutoSplit,
                 load_settings_on_open: bool = False,
                 load_settings_from_livesplit: bool = False):
    if load_settings_on_open:

        settings_files = []
        for file in os.listdir(auto_split_directory):
            if file.endswith(".pkl"):
                settings_files.append(file)

        # find all .pkls in AutoSplit folder, error if there is none or more than 1
        if len(settings_files) < 1:
            error_messages.noSettingsFileOnOpenError()
            self.last_loaded_settings = None
            return
        elif len(settings_files) > 1:
            error_messages.tooManySettingsFilesOnOpenError()
            self.last_loaded_settings = None
            return
        else:
            self.load_settings_file_path = os.path.join(
                auto_split_directory, settings_files[0])

    elif not load_settings_on_open and not load_settings_from_livesplit:

        self.load_settings_file_path = QtWidgets.QFileDialog.getOpenFileName(
            self, "Load Settings",
            os.path.join(auto_split_directory, "settings.pkl"),
            "PKL (*.pkl)")[0]

        if self.load_settings_file_path == '':
            return

    try:
        with open(self.load_settings_file_path, 'rb') as f:
            settings: List[Union[str, int]] = pickle.load(f)
            settings_count = len(settings)
            if settings_count < 18:
                if not load_settings_from_livesplit:
                    error_messages.oldVersionSettingsFileError()
                return
            # v1.3-1.4 settings. Add default pause_key and auto_start_on_reset_setting
            if settings_count == 18:
                settings.insert(9, '')
                settings.insert(20, 0)
            # v1.5 settings
            elif settings_count != 20:
                if not load_settings_from_livesplit:
                    error_messages.invalidSettingsError()
                return
            self.last_loaded_settings = [
                self.split_image_directory, self.similarity_threshold,
                self.comparison_index, self.pause, self.fps_limit,
                self.split_key, self.reset_key, self.skip_split_key,
                self.undo_split_key, self.pause_key, self.x, self.y,
                self.width, self.height, self.hwnd_title, _, _,
                self.group_dummy_splits_undo_skip_setting, self.loop_setting,
                self.auto_start_on_reset_setting
            ] = settings
    except (FileNotFoundError, MemoryError, pickle.UnpicklingError):
        # HACK / Workaround: Executing the error QMessageBox from the auto-controlled Worker Thread makes it hangs.
        # I don't like this solution as we should probably ensure the Worker works nicely with PyQt instead,
        # but in the mean time, this will do.
        if not load_settings_from_livesplit:
            error_messages.invalidSettingsError()
        return

    self.splitimagefolderLineEdit.setText(self.split_image_directory)
    self.similaritythresholdDoubleSpinBox.setValue(self.similarity_threshold)
    self.pauseDoubleSpinBox.setValue(self.pause)
    self.fpslimitSpinBox.setValue(self.fps_limit)
    self.xSpinBox.setValue(self.x)
    self.ySpinBox.setValue(self.y)
    self.widthSpinBox.setValue(self.width)
    self.heightSpinBox.setValue(self.height)
    self.comparisonmethodComboBox.setCurrentIndex(self.comparison_index)
    self.hwnd = win32gui.FindWindow(None, self.hwnd_title)

    # set custom checkbox's accordingly
    self.groupDummySplitsCheckBox.setChecked(
        self.group_dummy_splits_undo_skip_setting == 1)
    self.loopCheckBox.setChecked(self.loop_setting == 1)
    self.autostartonresetCheckBox.setChecked(
        self.auto_start_on_reset_setting == 1)
    self.autostartonresetCheckBox.setChecked(
        self.auto_start_on_reset_setting == 1)

    # TODO: Reuse code from hotkeys rather than duplicating here
    # try to set hotkeys from when user last closed the window
    try:
        keyboard.unhook_key(self.split_hotkey)
    # pass if the key is an empty string (hotkey was never set)
    except (AttributeError, KeyError):
        pass
    try:
        self.splitLineEdit.setText(self.split_key)
        if not self.is_auto_controlled:
            self.split_hotkey = keyboard.hook_key(
                self.split_key, lambda e: _hotkey_action(
                    e, self.split_key, self.startAutoSplitter))
    except (ValueError, KeyError):
        pass

    try:
        keyboard.unhook_key(self.reset_hotkey)
    except (AttributeError, KeyError):
        pass
    try:
        self.resetLineEdit.setText(self.reset_key)
        if not self.is_auto_controlled:
            self.reset_hotkey = keyboard.hook_key(
                self.reset_key,
                lambda e: _hotkey_action(e, self.reset_key, self.startReset))
    except (ValueError, KeyError):
        pass

    try:
        keyboard.unhook_key(self.skip_split_hotkey)
    except (AttributeError, KeyError):
        pass
    try:
        self.skipsplitLineEdit.setText(self.skip_split_key)
        if not self.is_auto_controlled:
            self.skip_split_hotkey = keyboard.hook_key(
                self.skip_split_key, lambda e: _hotkey_action(
                    e, self.skip_split_key, self.startSkipSplit))
    except (ValueError, KeyError):
        pass

    try:
        keyboard.unhook_key(self.undo_split_hotkey)
    except (AttributeError, KeyError):
        pass
    try:
        self.undosplitLineEdit.setText(self.undo_split_key)
        if not self.is_auto_controlled:
            self.undo_split_hotkey = keyboard.hook_key(
                self.undo_split_key, lambda e: _hotkey_action(
                    e, self.undo_split_key, self.startUndoSplit))
    except (ValueError, KeyError):
        pass

    try:
        keyboard.unhook_key(self.pause_hotkey)
    except (AttributeError, KeyError):
        pass
    try:
        self.pausehotkeyLineEdit.setText(self.pause_key)
        if not self.is_auto_controlled:
            self.pause_hotkey = keyboard.hook_key(
                self.pause_key,
                lambda e: _hotkey_action(e, self.pause_key, self.startPause))
    except (ValueError, KeyError):
        pass

    self.last_successfully_loaded_settings_file_path = self.load_settings_file_path
    self.checkLiveImage()