Пример #1
0
 def screen_height(self):
     return win32api.GetSystemMetrics(1)
Пример #2
0
    def check_for_reset(self):

        hwin = win32gui.GetDesktopWindow()

        width = win32api.GetSystemMetrics(win32con.SM_CXVIRTUALSCREEN)
        height = win32api.GetSystemMetrics(win32con.SM_CYVIRTUALSCREEN)
        left = win32api.GetSystemMetrics(win32con.SM_XVIRTUALSCREEN)
        top = win32api.GetSystemMetrics(win32con.SM_YVIRTUALSCREEN)

        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, (left, top), win32con.SRCCOPY)

        signedIntsArray = bmp.GetBitmapBits(True)
        img = np.frombuffer(signedIntsArray, dtype='uint8')

        # 4224 is total pixel width
        # 1080 is total monitor height
        img = img.reshape((1080,4224,4))
        
        srcdc.DeleteDC()
        memdc.DeleteDC()
        win32gui.ReleaseDC(hwin, hwindc)
        win32gui.DeleteObject(bmp.GetHandle())
        
        img = cv2.cvtColor(img, cv2.COLOR_BGRA2GRAY)

        resetcondition = False
        # ------------
        imgequal = img[956:1016, 1280+1220:1280+1280]
        result=cv2.matchTemplate(imgequal,self.imgequal,cv2.TM_CCOEFF_NORMED)
        _, max_val, _, _ = cv2.minMaxLoc(result)


        if max_val < 0.6:
            print("inventory full, resetting day")
            #print("imgequal less than 0.6: {}".format(max_val))
            resetcondition = True

        if not resetcondition:
            # ------------
            tired = img[995:1005, 1280+1880:1280+1895]
            #cv2.imwrite("test.png", tired)
            result=cv2.matchTemplate(tired,self.tired,cv2.TM_CCOEFF_NORMED)
            _, max_val, _, _ = cv2.minMaxLoc(result)
            if max_val > 0.99:
                print(r"I'm tired, resetting day")
                #print("imgtired over 0.4: {}".format(max_val))
                resetcondition = True

        if not resetcondition:
            # ------------
            # 12 : xx am coords
            late = img[147:179, 1280+1731:1280+1882]
            # check if 12
            result=cv2.matchTemplate(late,self.twelve,cv2.TM_CCOEFF_NORMED)
            _, max_val, _, _ = cv2.minMaxLoc(result)
            if max_val > 0.95:
                result=cv2.matchTemplate(late,self.am,cv2.TM_CCOEFF_NORMED)
                _, max_val, _, _ = cv2.minMaxLoc(result)
                if max_val > 0.95:
                    print(r"It's late, resetting day")
                    resetcondition = True
       
        #cv2.imwrite("test.png", late)
        #sys.exit()
        return resetcondition
Пример #3
0
                value = hwnds[hwnd]
                enabled = value[1]
                hwnds[hwnd] = [win32gui.GetWindowText(hwnd), enabled]
            else:
                hwnds[hwnd] = [win32gui.GetWindowText(hwnd), True]


hwnds = {}

prevclickstate = -1
#HOTKEYS
VK_F1 = 0x70
VK_F2 = 0x71
VK_F3 = 0x72

desktopWidth = win32api.GetSystemMetrics(0)
desktopHeight = win32api.GetSystemMetrics(1)


def cls():
    os.system('cls' if os.name == 'nt' else 'clear')


def updatewindow():
    win32gui.EnumWindows(enumHandler, hwnds)
    cls()
    print("[F1] TOGGLE ACTIVE WINDOW SCRIPT")
    print("[F2] TOGGLE ALL WINDOWS")
    print("[F3] DISABLE ALL WINDOWS")
    print("------------------------------------------")
    for key in hwnds:
Пример #4
0
import os
import pyautogui
import webbrowser
pyautogui.PAUSE = 0.5
time.sleep(1)
#pyautogui.hotkey("win")
screenWidth, screenHeight = pyautogui.size()
currentMouseX, currentMouseY = pyautogui.position()
print(currentMouseX)
print(currentMouseY)
webbrowser.open("http://www.163.com")
#os.system(r'"C:/Program Files/Internet Explorer/iexplore.exe" http://www.163.com')
time.sleep(8)
pyautogui.moveTo(449, 266)
pyautogui.click()

w = win32api.GetSystemMetrics(win32con.SM_CXSCREEN)
h = win32api.GetSystemMetrics(win32con.SM_CYSCREEN)

while True:
    time.sleep(2)
    print(w)
    print(h)
    localtime = time.asctime(time.localtime((time.time())))
    file1 = open("C:/Users/meng/Desktop/test.txt", "a")
    file1.writelines(str(w))
    file1.writelines(str(h))
    file1.writelines("----------------------")
    file1.writelines(localtime + "\n")
    file1.close()
Пример #5
0
def cmd_fullscreen(ensoapi):
    """ Put window into full-screen mode """
    win = DESK.GetForegroundWindow()
    logging.debug(win)
    style = win32gui.GetWindowLong(win.GetHwnd(), win32con.GWL_STYLE)
    logging.debug(style)
    if style & (win32con.WS_CAPTION | win32con.WS_SIZEBOX) == 0:
        TASKBAR.undo_set_autohide()

        # Revert the fullscreen
        style = style | win32con.WS_CAPTION | win32con.WS_SIZEBOX
        logging.debug(style)
        win32gui.SetWindowLong(win.GetHwnd(), win32con.GWL_STYLE, style)
        if fullscreen_windows.get(win.GetHwnd()):
            (original_left, original_top, original_right, original_bottom,
             maximized) = fullscreen_windows[win.GetHwnd()]
            win32gui.SetWindowPos(
                win.GetHwnd(), win32con.HWND_NOTOPMOST, original_left,
                original_top, original_right - original_left,
                original_bottom - original_top,
                win32con.SWP_NOOWNERZORDER | win32con.SWP_NOSENDCHANGING)
            if maximized:
                win.SetAsForegroundWindow()
                win.Maximize()
                #time.sleep(0.4)
            else:
                win.Restore()
            """
            win32gui.SetWindowPos(
                win.GetHwnd(),
                win32con.HWND_TOP,
                original_left,
                original_top,
                original_right - original_left,
                original_bottom - original_top,
                win32con.SWP_NOMOVE | win32con.SWP_NOSIZE)
            """
            #win.SetAsForegroundWindow()
            del fullscreen_windows[win.GetHwnd()]
    else:
        TASKBAR.set_autohide(True)

        placement = win32gui.GetWindowPlacement(win.GetHwnd())
        maximized = placement[1] == win32con.SW_MAXIMIZE
        print("maximized: " + repr(maximized))

        (original_left, original_top, original_right,
         original_bottom) = win32gui.GetWindowRect(win.GetHwnd())
        # Make fulscreen
        #ex_style = win32gui.GetWindowLong(win.GetHwnd(), win32con.GWL_EXSTYLE)
        #ex_style = ex_style | win32con.WS_EX_TOPMOST
        #win32gui.SetWindowLong(win.GetHwnd(), win32con.GWL_EXSTYLE, ex_style)

        style = style & ~(win32con.WS_CAPTION | win32con.WS_SIZEBOX)
        print(style)
        win32gui.SetWindowLong(win.GetHwnd(), win32con.GWL_STYLE, style)

        menu_height = win32api.GetSystemMetrics(win32con.SM_CYMENU)
        width = win32api.GetSystemMetrics(0)
        height = win32api.GetSystemMetrics(1)
        win32gui.SetWindowPos(
            win.GetHwnd(),
            win32con.HWND_TOP,  # TOPMOST
            0,
            -menu_height,
            width,
            height + menu_height - 1,
            win32con.SWP_SHOWWINDOW)

        #win.Maximize()
        #win.BringToTop()

        fullscreen_windows[win.GetHwnd()] = (original_left, original_top,
                                             original_right, original_bottom,
                                             maximized)

    win.UpdateWindow()
Пример #6
0
 def _determine_fullscreen_resolution(self):
     if is_windows():
         return [win32api.GetSystemMetrics(0), win32api.GetSystemMetrics(1)]
     else:
         monitors = mss.mss().monitors
         return monitors[0]["width"], monitors[0]["height"]
Пример #7
0
 def get_screen_resolution(self):
     width = win32api.GetSystemMetrics(0)
     height = win32api.GetSystemMetrics(1)
     return width, height
Пример #8
0
def screen_size():
    return (win32api.GetSystemMetrics(0), win32api.GetSystemMetrics(1))
Пример #9
0
def mousemove(x, y):
    nx = x * 65535 / win32api.GetSystemMetrics(0)
    ny = y * 65535 / win32api.GetSystemMetrics(1)
    win32api.mouse_event(win32con.MOUSEEVENTF_ABSOLUTE | \
       win32con.MOUSEEVENTF_MOVE, nx, ny)
Пример #10
0
import requests, datetime, time, win32api
import numpy as np
import matplotlib.pyplot as plt
from decimal import Decimal

#pip install pywin32

screenWidth = win32api.GetSystemMetrics(0)
screenHeight = win32api.GetSystemMetrics(1)


def generateData(apiKey, numDataPoints, startingPoint):
    #generate timepoints (plot's x axis)
    current_unix_time = time.time()  # seconds from unix epoch
    start_unix_time = current_unix_time - (startingPoint * 24 * 60 * 60)
    unix_time_points = np.linspace(start_unix_time, current_unix_time,
                                   numDataPoints)
    time_points = [
        datetime.datetime.fromtimestamp(x).strftime('%Y-%m-%d')
        for x in unix_time_points
    ]  # convert to YYYY-MM-DD format
    time_points = np.array(time_points)

    # download currency data, format: {'symbol': 'name'}
    url = f"http://apilayer.net/api/list?access_key={apiKey}"
    res = requests.get(url)
    res.raise_for_status()
    data = res.json()
    currencies = data['currencies']

    # manage exclusions
Пример #11
0
def resolution():
    return win32api.GetSystemMetrics(0), win32api.GetSystemMetrics(1)
Пример #12
0
    mK_serial_port = serial_ports[0]
print('port=', serial_ports)

mk_connection = None
try:
    mk_connection = serial.Serial(mK_serial_port, baudrate=128000, timeout=0.1)
    device = constant.PSYCHO_TOOLBOX
except:
    print('MilliKey device not available')

results = []
ww = 1
wh = 1
FlagFull = False
try:
    ww = win32api.GetSystemMetrics(0)
    wh = win32api.GetSystemMetrics(1)
    FlagFull = True
except:
    print('Full screen mode not available')

if FlagFull:
    parameters['ScreenSize'] = (ww, wh)
    parameters['FullScr'] = True

# visual stimuli
ExpWin = c_visual.get_exp_win(parameters)

# fixation cross
FLine1 = c_visual.get_cross_line_1(ExpWin, parameters)
FLine2 = c_visual.get_cross_line_2(ExpWin, parameters)
Пример #13
0
    def set_icon_from_data(self, pixels, has_alpha, w, h, rowstride):
        #TODO: use native code somehow to avoid saving to file
        log("set_icon_from_data%s",
            ("%s pixels" % len(pixels), has_alpha, w, h, rowstride))
        from PIL import Image, ImageOps  #@UnresolvedImport
        if has_alpha:
            rgb_format = "RGBA"
        else:
            rgb_format = "RGB"
        img = Image.frombuffer(rgb_format, (w, h), pixels, "raw", rgb_format,
                               0, 1)
        #apparently, we have to use SM_CXSMICON (small icon) and not SM_CXICON (regular size):
        size = win32api.GetSystemMetrics(win32con.SM_CXSMICON)
        if w != h or w != size:
            img = img.resize((size, size), Image.ANTIALIAS)
        if has_alpha:
            #extract alpha channel as mask into an inverted "L" channel image:
            data_fn = getattr(img, "tobytes", getattr(img, "tostring", None))
            alpha = data_fn("raw", "A")
            from_fn = getattr(Image, "frombytes",
                              getattr(Image, "fromstring", None))
            mask = from_fn("L", img.size, alpha)
            mask = ImageOps.invert(mask)
            #strip alpha from pixels:
            img = img.convert("RGB")
        else:
            #no alpha: just use image as mask:
            mask = img

        def img_to_bitmap(image, pixel_value):
            hdc = win32gui.CreateCompatibleDC(0)
            dc = win32gui.GetDC(0)
            hbm = win32gui.CreateCompatibleBitmap(dc, size, size)
            hbm_save = win32gui.SelectObject(hdc, hbm)
            for x in range(size):
                for y in range(size):
                    pixel = image.getpixel((x, y))
                    v = pixel_value(pixel)
                    win32gui.SetPixelV(hdc, x, y, v)
            win32gui.SelectObject(hdc, hbm_save)
            win32gui.ReleaseDC(self.hwnd, hdc)
            win32gui.ReleaseDC(self.hwnd, dc)
            return hbm

        hicon = FALLBACK_ICON
        try:

            def rgb_pixel(pixel):
                r, g, b = pixel[:3]
                return r + g * 256 + b * 256 * 256

            bitmap = img_to_bitmap(img, rgb_pixel)
            if mask is img:
                mask_bitmap = bitmap
            else:
                #mask is in "L" mode, so we get the pixel value directly from getpixel(x, y)
                def mask_pixel(l):
                    return l + l * 256 + l * 256 * 256

                mask_bitmap = img_to_bitmap(mask, mask_pixel)
            if mask_bitmap:
                pyiconinfo = (True, 0, 0, mask_bitmap, bitmap)
                hicon = win32gui.CreateIconIndirect(pyiconinfo)
                log("CreateIconIndirect(%s)=%s", pyiconinfo, hicon)
                if hicon == 0:
                    hicon = FALLBACK_ICON
            self.do_set_icon(hicon)
            win32gui.UpdateWindow(self.hwnd)
        except:
            log.error("error setting icon", exc_info=True)
        finally:
            #DeleteDC(dc)
            if hicon != FALLBACK_ICON:
                win32gui.DestroyIcon(hicon)
Пример #14
0
 def screen_size(self):
     width = win32api.GetSystemMetrics(0)
     height = win32api.GetSystemMetrics(1)
     return width, height
    def __init__(self):

    #screen
        self.screen_width = win32api.GetSystemMetrics(win32con.SM_CXSCREEN)
        self.screen_height = win32api.GetSystemMetrics(win32con.SM_CYSCREEN)
        self.bg_color = (0,0,0)
        self.fullscreen = True
        self.screen = pygame.display.set_mode(
                    (self.screen_width,self.screen_height),pygame.FULLSCREEN)
        self.screen_rect = self.screen.get_rect()
    
    #red half bg - used to indicate who goes first
        self.half_red_bg = pygame.Rect(0,0,int(self.screen_width/2),
                                                    self.screen_height)
        self.color_red = (255,0,0)

    #bg image
        f=r'images\1536_864.jpg'
        try:
            bg_image = pygame.image.load(f)
        except FileNotFoundError:
            f=r'C:\Users\AAAAA\Desktop\python_work\battle_chess\images\1536_864.jpg'
            bg_image = pygame.image.load(f)
        self.bg_image_width = int(self.screen_width/1.32)
        self.bg_image_height = int(1147*self.bg_image_width/1749)
        bg_image_size = (self.bg_image_width,self.bg_image_height)
        self.bg_image = pygame.transform.scale(bg_image,bg_image_size)
        self.bg_image_rect = self.bg_image.get_rect()
        self.bg_image_rect.center = self.screen_rect.center

    #mouse image
    #palm image
        f = r'images\palm.png'
        try:
            palm_image = pygame.image.load(f)
        except FileNotFoundError:
            f=r'C:\Users\AAAAA\Desktop\python_work\battle_chess\images\palm.png'
            palm_image = pygame.image.load(f)
        self.palm_image_width = int(self.screen_width/1280*25)
        self.palm_image_height = self.palm_image_width
        palm_image_size = (self.palm_image_width,self.palm_image_height)
        self.palm_image = pygame.transform.scale(palm_image,palm_image_size)
        self.palm_image_rect = self.palm_image.get_rect()
    #fist image
        f = r'images\fist.png'
        try:
            fist_image = pygame.image.load(f)
        except FileNotFoundError:
            f=r'C:\Users\AAAAA\Desktop\python_work\battle_chess\images\fist.png'
            fist_image = pygame.image.load(f)
        self.fist_image_width = int(self.screen_width/1280*25*1.2)
        self.fist_image_height = self.fist_image_width
        fist_image_size = (self.fist_image_width,self.fist_image_height)
        self.fist_image = pygame.transform.scale(fist_image,fist_image_size)
        self.fist_image_rect = self.fist_image.get_rect()
    #mouse image
        self.mouse_image = self.palm_image
        self.mouse_image_rect = self.mouse_image.get_rect()

    #mouse enter pygame display
        self.mouse_enter = False

    #win_image
        f = r'images\victory.jpg'
        try:
            self.win_image = pygame.image.load(f).convert()
        except FileNotFoundError:
            f=r'C:\Users\AAAAA\Desktop\python_work\battle_chess\images\victory.jpg'
            self.win_image = pygame.image.load(f).convert()
        self.alpha_value = 0
        self.win_image_width = int(self.screen_width/1280*774)
        self.win_image_height = int(self.win_image_width/774*215)
        win_image_size = (self.win_image_width,self.win_image_height)
        self.win_image = pygame.transform.scale(self.win_image,win_image_size)

    #tie image
    #normal
        f = r'images\tie_flag.png'
        try:
            self.tie_image = pygame.image.load(f)
        except FileNotFoundError:
            f=r'C:\Users\AAAAA\Desktop\python_work\battle_chess\images\tie_flag.png'
            self.tie_image = pygame.image.load(f)
        self.tie_image_width = int(5*self.screen_width/128)
        self.tie_image_height = self.tie_image_width
        tie_image_size = (self.tie_image_width,self.tie_image_height)
        self.tie_image = pygame.transform.scale(self.tie_image,tie_image_size)
        self.tie_image_rect = self.tie_image.get_rect()
        self.tie_image_rect.bottom = self.screen_rect.bottom
        self.tie_image_rect.left=self.screen_rect.left+self.screen_width/64
    #big
        self.tie_imageb = pygame.image.load(f)
        self.tie_imageb_width = int(60*self.screen_width/128)
        self.tie_imageb_height = self.tie_imageb_width
        tie_imageb_size = (self.tie_imageb_width,self.tie_imageb_height)
        self.tie_imageb=pygame.transform.scale(self.tie_imageb,tie_imageb_size)
        self.tie_imageb_rect = self.tie_imageb.get_rect()
        self.tie_imageb_rect.centerx = self.screen_rect.centerx
        self.tie_imageb_rect.centery = -self.tie_imageb_height/2
    #transparent
        f = r'images\tie_flagt.png'
        try:
            self.tie_imaget = pygame.image.load(f)
        except FileNotFoundError:
            f=r'C:\Users\AAAAA\Desktop\python_work\battle_chess\images\tie_flagt.png'
            self.tie_imaget = pygame.image.load(f)
        self.tie_imaget = pygame.transform.scale(self.tie_imaget,tie_image_size)
        self.tie_imaget_rect = self.tie_imaget.get_rect()
        self.tie_imaget_rect.bottom = self.screen_rect.bottom
        self.tie_imaget_rect.left=self.screen_rect.left+self.screen_width/64
    #tie flag
        self.tie_flag = self.tie_imaget
        self.tie_flag_rect = self.tie_imaget_rect

    #white flag image
    #normal
        f = r'images\wh_flag.png'
        try:
            self.wh_image = pygame.image.load(f)
        except FileNotFoundError:
            f=r'C:\Users\AAAAA\Desktop\python_work\battle_chess\images\wh_flag.png'
            self.wh_image = pygame.image.load(f)
        self.wh_image_width = self.tie_image_width
        wh_image_size = (self.wh_image_width,self.wh_image_width)
        self.wh_image = pygame.transform.scale(self.wh_image,wh_image_size)
        self.wh_image_rect = self.wh_image.get_rect()
        self.wh_image_rect.bottom = self.screen_rect.bottom
        self.wh_image_rect.left=self.tie_imaget_rect.right+3*self.screen_width/128
    #transparent
        f = r'images\wh_flagt.png'
        try:
            self.wht_image = pygame.image.load(f)
        except FileNotFoundError:
            f=r'C:\Users\AAAAA\Desktop\python_work\battle_chess\images\wh_flagt.png'
            self.wht_image = pygame.image.load(f)
        self.wht_image = pygame.transform.scale(self.wht_image,wh_image_size)
        self.wht_image_rect = self.wht_image.get_rect()
        self.wht_image_rect.bottom = self.screen_rect.bottom
        self.wht_image_rect.left=self.tie_imaget_rect.right+3*self.screen_width/128
    #white flag
        self.wh_flag = self.wht_image
        self.wh_flag_rect = self.wht_image_rect

    #detective image used for blit flag image
        self.detec_width = 250*self.screen_width/1280
        self.detec_height = 150*self.screen_width/1280
        self.detec_rect = pygame.Rect(0,0,self.detec_width,self.detec_height)
        self.detec_rect.bottomleft = self.screen_rect.bottomleft

        self.detec_active = False

    #notice board
        self.board_width = self.screen_width
        self.board_height = int(self.screen_width/12.8)
        self.board_color = (0,42,255)
        self.notice_color = (255,255,255)
        self.yesorno_lining_width = int(self.screen_width/12.8)
        self.yesorno_lining_height = int(self.yesorno_lining_width*3/10)
        self.yesorno_width = int(self.yesorno_lining_width*0.96)
        self.yesorno_height = int(self.yesorno_lining_height*0.9)
        self.yesorno_lining_color = (255,255,255)
        self.yesorno_color = (0,190,255)
        self.yesorno_colort = (0,160,255)
        self.yesno_spacing = int(self.yesorno_lining_width*3/10)
        self.board_font = pygame.font.SysFont('calibri',23)
        self.board_appear = False

        self.board = None
    
    #chess
        self.chess_width_out = self.screen_width/26.4
        self.chess_height_out = self.chess_width_out*1.6
        self.chess_width_in = self.chess_width_out*0.85
        self.chess_height_in = self.chess_height_out*0.85
        self.chess_color_back = (0,0,0)
        self.chess_color_front = (255,255,255)
        self.chess_color_selected = (0,255,0)
        self.text_color_red = (255,0,0)
        self.text_color_black = (0,0,0)
        #get proper font size
        active = True
        self.fontsize = 1
        while active:
            self.font = pygame.font.SysFont('华文楷体',self.fontsize,0)
            self.test_image = self.font.render('测试',True,(0,0,0))
            self.test_image = pygame.transform.rotate(self.test_image,90)
            self.test_image_rect = self.test_image.get_rect()
            if self.test_image_rect[2] <= self.chess_width_in:
                self.fontsize += 1
            else:
                active = False
        self.font = pygame.font.SysFont('华文楷体',self.fontsize-1,0)
        #distribute chess position
        self.pos_num = 0

    #play button
        self.play_width_out = int(self.screen_width*25/192)
        self.play_height_out = int(self.play_width_out*0.4)
        self.play_width_in = int(self.play_width_out*0.92)
        self.play_height_in = int(self.play_height_out*0.8)
        self.play_button_color_in_1 = (0,230,0)
        self.play_button_color_in_2 = (0,200,0)
        self.play_button_color_out = (0,255,0)
        self.play_text_color = (0,0,0)
        self.play_font = pygame.font.SysFont('calibri',self.fontsize-1)

    #chess lines and rows spacing
        self.line_1_pos_x = (self.screen_width-self.bg_image_width)/2
        self.line_1_pos_x += self.bg_image_width/23
        self.line_1_pos_y = (self.screen_height-self.bg_image_height)/2
        self.line_1_pos_y += self.bg_image_height*0.084976308
        self.line_norm_spac = self.bg_image_width*83/1150
        self.line_spac_spec_1 = self.line_norm_spac*6/5 
        self.line_spac_spec_2 = self.line_norm_spac*5.8/2.5
        self.row_spac = self.line_norm_spac*4.7/2.5

    #dead chess spacing
        self.dead_pos_x = self.chess_height_out/2
        self.dead_pos_y = 0

    #chess pool
        self.chess_pool = [
            ('军旗',-2,self.text_color_red),('地雷',-1,self.text_color_red),
            ('地雷',-1,self.text_color_red),('地雷',-1,self.text_color_red),
            ('军旗',-2,self.text_color_black),('地雷',-1,self.text_color_black),
            ('地雷',-1,self.text_color_black),('地雷',-1,self.text_color_black),
            ('炸弹',0,self.text_color_red),('炸弹',0,self.text_color_red),
            ('炸弹',0,self.text_color_black),('炸弹',0,self.text_color_black),
            ('工兵',1,self.text_color_red),('工兵',1,self.text_color_red),
            ('工兵',1,self.text_color_red),('工兵',1,self.text_color_black),
            ('工兵',1,self.text_color_black),('工兵',1,self.text_color_black),
            ('排长',2,self.text_color_red),('排长',2,self.text_color_red),
            ('排长',2,self.text_color_red),('排长',2,self.text_color_black),
            ('排长',2,self.text_color_black),('排长',2,self.text_color_black),
            ('连长',3,self.text_color_red),('连长',3,self.text_color_red),
            ('连长',3,self.text_color_red),('连长',3,self.text_color_black),
            ('连长',3,self.text_color_black),('连长',3,self.text_color_black),
            ('营长',4,self.text_color_red),('营长',4,self.text_color_red),
            ('营长',4,self.text_color_black),('营长',4,self.text_color_black),
            ('团长',5,self.text_color_red),('团长',5,self.text_color_red),
            ('团长',5,self.text_color_black),('团长',5,self.text_color_black),
            ('旅长',6,self.text_color_red),('旅长',6,self.text_color_red),
            ('旅长',6,self.text_color_black),('旅长',6,self.text_color_black),
            ('师长',7,self.text_color_red),('师长',7,self.text_color_red),
            ('师长',7,self.text_color_black),('师长',7,self.text_color_black),
            ('军长',8,self.text_color_red),('军长',8,self.text_color_black),
            ('司令',9,self.text_color_red),('司令',9,self.text_color_black)
            ]

    #game status
        self.red_mine = 3
        self.black_mine = 3

        self.second = False
        #the two selected chess to move
        self.chess_1 = None
        self.chess_2 = None
        #chess_1 index cache
        self.chess1index = None
        #create an unchangable chesses index, used for determine move position
        #b/c at that time the moved one is removed from chesses
        #why need this? b/c in the determine_mov_pos func, it will need the index to locate.
        self.chesses = None
        #chess_1 center position cache used for moving chess_1, does not effect undo
        self.a = None
        #chess_1 moves with mouse
        self.chess_move = False

        self.dead_pool = []
        self.dead_num = 0
        #used to undo
        self.allow_undo = False

        #used to determine who's red and who's black
        self.color_confirmed = False
        self.count = 0
        self.move_1 = None      #used for determine who's red or black in func color_confirmed

        #used to determine who's turn is it, players MUST take turns to go
        #the alter_move_control is placed in the check ingame event func
        self.move_control = 0

        #put game win and game tie in game result as strs.
        self.game_result = None
        #game end is true when before pushing the play button, or a round ends
        self.game_end = True
        #determine whether one can admit tie or lose
        self.game_allow_end = False
        #when notice board pop up, game will not be active
        self.game_active = True
        #control game rewind, used in func rewind
        self.game_rewind = False
        #used to control if one side has no pieces then game end
        self.red_no_pieces = True
        self.black_no_pieces = True
        #used to indicate who goes first
        self.red_bg = False
        #used to show the order of play, also control the duration-3seconds
        self.show_order = False
        #used to show play button at the beginning
        self.play_button_on = True
        self.play_button = None
        #moved chess cache used for undo
        self.move_cache = []

        #used to compare steps moved to the records; and calculate time duration only once
        self.calculating = True
        #store the stat image
        self.draw_stat = None
        
        #calculate game duration, the start_time is stored right after botton click detected
        #end_time is stored when game result is win or tie in func update_screen
        self.start_time = None
        self.end_time = None

    #game statistics, reset each round
        self.player_1 = 'player1'
        self.player_2 = 'player2'
        #default: left -> player 1
        self.first_move = None
        self.steps_before_c_confirmed = 0
        self.player_1_color = None
        self.move_start = 0
        self.move_end = 0
        self.p1_movtime = 0
        self.p2_movtime = 0
        self.p1_steps = 0
        self.p2_steps = 0
        self.p1_units_destroyed = 0
        self.p2_units_destroyed = 0
        self.winner = None
        self.total_time_lasted = None
        self.total_steps_moved = None
    #win music
        f = r'victory.ogg'
        try:
            self.win_music = pygame.mixer.Sound(f)
        except FileNotFoundError:
            f=r'C:\Users\AAAAA\Desktop\python_work\battle_chess\victory.ogg'
            self.win_music = pygame.mixer.Sound(f)
        self.win_music.set_volume(0.2)
        self.win_music_play = False

    #variables related to free fall
        self.time_count = 0
        self.v = 0
        self.v_0 = 0
        self.down = True
        self.up = False
        self.x_0 = -self.tie_imageb_height/2
        self.y = 0

        self.free_fall = True
Пример #16
0
def screen_size():
    return windows.GetSystemMetrics(0), windows.GetSystemMetrics(1)
Пример #17
0
import win32api, win32con

from PIL import Image

x = win32api.GetSystemMetrics(win32con.SM_CXSCREEN)  # 获得屏幕分辨率X轴
y = win32api.GetSystemMetrics(win32con.SM_CYSCREEN)  # 获得屏幕分辨率Y轴


def SetImgPixel(width, height, pic):
    for i in range(width):
        for k in range(height):
            color = pic.getpixel((i, k))
            color = color[:-1] + (100, )
            pic.putpixel((i, k), color)


img = Image.open(r'C:\wall.jpg')
x, y = img.size

BlackTrans = Image.new("RGBA", (x, y), "Black")
x1, y1 = BlackTrans.size
SetImgPixel(x1, y1, BlackTrans)

img.paste(BlackTrans, (0, 0), BlackTrans)
img.save(r'C:\Users\Anteayer\Desktop\txt.png')
Пример #18
0
    def run_script_once(cls, script_path, thd=None):
        s = open(script_path, 'r').read()
        s = json.loads(s.replace('],\n]', ']\n]'))
        steps = len(s)

        sw = win32api.GetSystemMetrics(win32con.SM_CXSCREEN)
        sh = win32api.GetSystemMetrics(win32con.SM_CYSCREEN)

        for i in range(steps):

            print(s[i])

            delay = s[i][0]
            event_type = s[i][1].upper()
            message = s[i][2].lower()
            action = s[i][3]

            time.sleep(delay / 1000.0)

            if thd:
                current_status = thd.frame.tnumrd.GetLabel()
                if current_status in ['broken', 'finished']:
                    break
                thd.event.wait()
                text = '%s  [%d/%d %d/%d]' % (thd.running_text, i + 1, steps,
                                              thd.j, thd.run_times)
                thd.frame.tnumrd.SetLabel(text)

            if event_type == 'EM':
                x, y = action

                # ctypes.windll.user32.SetCursorPos(x, y)
                # win32api.SetCursorPos([x, y])

                nx = int(x * 65535 / sw)
                ny = int(y * 65535 / sh)
                win32api.mouse_event(
                    win32con.MOUSEEVENTF_ABSOLUTE | win32con.MOUSEEVENTF_MOVE,
                    nx, ny, 0, 0)

                if message == 'mouse left down':
                    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, 0, 0,
                                         0, 0)
                elif message == 'mouse left up':
                    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, 0, 0, 0,
                                         0)
                elif message == 'mouse right down':
                    win32api.mouse_event(win32con.MOUSEEVENTF_RIGHTDOWN, 0, 0,
                                         0, 0)
                elif message == 'mouse right up':
                    win32api.mouse_event(win32con.MOUSEEVENTF_RIGHTUP, 0, 0, 0,
                                         0)
                elif message == 'mouse move':
                    pass
                else:
                    print('unknow mouse event:', message)

            elif event_type == 'EK':
                key_code, key_name, extended = action

                # shift ctrl alt
                # if key_code >= 160 and key_code <= 165:
                #     key_code = int(key_code/2) - 64

                base = 0
                if extended:
                    base = win32con.KEYEVENTF_EXTENDEDKEY

                if message == 'key down':
                    win32api.keybd_event(key_code, 0, base, 0)
                elif message == 'key up':
                    win32api.keybd_event(key_code, 0,
                                         base | win32con.KEYEVENTF_KEYUP, 0)
                else:
                    print('unknow keyboard event:', message)

            elif event_type == 'EX':

                if message == 'input':
                    text = action
                    pyperclip.copy(text)
                    # Ctrl+V
                    win32api.keybd_event(162, 0, 0, 0)  # ctrl
                    win32api.keybd_event(86, 0, 0, 0)  # v
                    win32api.keybd_event(86, 0, win32con.KEYEVENTF_KEYUP, 0)
                    win32api.keybd_event(162, 0, win32con.KEYEVENTF_KEYUP, 0)
                else:
                    print('unknow extra event:', message)
Пример #19
0
assert new_w == w + 1
assert new_h == h + 2
assert new_t == t + 3

win32gui.SystemParametersInfo(win32con.SPI_SETMOUSEHOVERWIDTH, w)
win32gui.SystemParametersInfo(win32con.SPI_SETMOUSEHOVERHEIGHT, h)
win32gui.SystemParametersInfo(win32con.SPI_SETMOUSEHOVERTIME, t)
new_w = win32gui.SystemParametersInfo(win32con.SPI_GETMOUSEHOVERWIDTH)
new_h = win32gui.SystemParametersInfo(win32con.SPI_GETMOUSEHOVERHEIGHT)
new_t = win32gui.SystemParametersInfo(win32con.SPI_GETMOUSEHOVERTIME)
assert new_w == w
assert new_h == h
assert new_t == t

print "SPI_SETDOUBLECLKWIDTH, SPI_SETDOUBLECLKHEIGHT"
x = win32api.GetSystemMetrics(win32con.SM_CXDOUBLECLK)
y = win32api.GetSystemMetrics(win32con.SM_CYDOUBLECLK)
print 'x,y:', x, y
win32gui.SystemParametersInfo(win32con.SPI_SETDOUBLECLKWIDTH, x + 1)
win32gui.SystemParametersInfo(win32con.SPI_SETDOUBLECLKHEIGHT, y + 2)
new_x = win32api.GetSystemMetrics(win32con.SM_CXDOUBLECLK)
new_y = win32api.GetSystemMetrics(win32con.SM_CYDOUBLECLK)
print 'new x,y:', new_x, new_y
assert new_x == x + 1
assert new_y == y + 2
win32gui.SystemParametersInfo(win32con.SPI_SETDOUBLECLKWIDTH, x)
win32gui.SystemParametersInfo(win32con.SPI_SETDOUBLECLKHEIGHT, y)
new_x = win32api.GetSystemMetrics(win32con.SM_CXDOUBLECLK)
new_y = win32api.GetSystemMetrics(win32con.SM_CYDOUBLECLK)
assert new_x == x
assert new_y == y
Пример #20
0
    def _SetupList(self):
        child_style = (win32con.WS_CHILD
                       | win32con.WS_VISIBLE
                       | win32con.WS_BORDER
                       | win32con.WS_HSCROLL
                       | win32con.WS_VSCROLL)
        child_style |= (commctrl.LVS_SINGLESEL | commctrl.LVS_SHOWSELALWAYS
                        | commctrl.LVS_REPORT)
        self.hwndList = win32gui.CreateWindow(
            "SysListView32",
            None,
            child_style,
            0,
            0,
            100,
            100,
            self.hwnd,
            IDC_LISTBOX,
            self.hinst,
            None,
        )

        child_ex_style = win32gui.SendMessage(
            self.hwndList, commctrl.LVM_GETEXTENDEDLISTVIEWSTYLE, 0, 0)
        child_ex_style |= commctrl.LVS_EX_FULLROWSELECT
        win32gui.SendMessage(self.hwndList,
                             commctrl.LVM_SETEXTENDEDLISTVIEWSTYLE, 0,
                             child_ex_style)

        # Add an image list - use the builtin shell folder icon - this
        # demonstrates the problem with alpha-blending of icons on XP if
        # winxpgui is not used in place of win32gui.
        il = win32gui.ImageList_Create(
            win32api.GetSystemMetrics(win32con.SM_CXSMICON),
            win32api.GetSystemMetrics(win32con.SM_CYSMICON),
            commctrl.ILC_COLOR32 | commctrl.ILC_MASK,
            1,  # initial size
            0,
        )  # cGrow

        shell_dll = os.path.join(win32api.GetSystemDirectory(), "shell32.dll")
        large, small = win32gui.ExtractIconEx(shell_dll, 4, 1)
        win32gui.ImageList_ReplaceIcon(il, -1, small[0])
        win32gui.DestroyIcon(small[0])
        win32gui.DestroyIcon(large[0])
        win32gui.SendMessage(self.hwndList, commctrl.LVM_SETIMAGELIST,
                             commctrl.LVSIL_SMALL, il)

        # Setup the list control columns.
        lvc = LVCOLUMN(mask=commctrl.LVCF_FMT
                       | commctrl.LVCF_WIDTH
                       | commctrl.LVCF_TEXT
                       | commctrl.LVCF_SUBITEM)
        lvc.fmt = commctrl.LVCFMT_LEFT
        lvc.iSubItem = 1
        lvc.text = "Title"
        lvc.cx = 200
        win32gui.SendMessage(self.hwndList, commctrl.LVM_INSERTCOLUMN, 0,
                             lvc.toparam())
        lvc.iSubItem = 0
        lvc.text = "Order"
        lvc.cx = 50
        win32gui.SendMessage(self.hwndList, commctrl.LVM_INSERTCOLUMN, 0,
                             lvc.toparam())

        win32gui.UpdateWindow(self.hwnd)
Пример #21
0
def screen_dimensions():
    return [win32api.GetSystemMetrics(0), win32api.GetSystemMetrics(1)]
Пример #22
0
    def _make_crop(self) -> Optional[Crop]:
        if self.fullscreen or self.borderless:
            return None
        else:
            if dpi_detection:
                mon = ctypes.windll.user32.MonitorFromWindow(self.hwnd, 1)
                dpiX, dpiY = ctypes.wintypes.UINT(), ctypes.wintypes.UINT()
                ctypes.windll.shcore.GetDpiForMonitor(mon, 0,
                                                      ctypes.byref(dpiX),
                                                      ctypes.byref(dpiY))
                scale = dpiX.value / 96
            else:
                scale = 11

            if self.maximised:
                title_height = int(
                    ctypes.windll.user32.GetSystemMetrics(SM_CYCAPTION) *
                    scale + 0.5)
                x_offset = 0
            else:
                title_height = int(
                    (win32api.GetSystemMetrics(SM_CYFRAME) +
                     win32api.GetSystemMetrics(SM_CYCAPTION) +
                     win32api.GetSystemMetrics(SM_CXPADDEDBORDER)) * scale +
                    0.5)
                x_offset = 1

            # Find window location in monitor-relative space
            screenspace_left = self.true_rect.left
            screenspace_top = self.true_rect.top + title_height
            screenspace_right = screenspace_left + self.true_rect.width - 1
            sceenspace_bottom = screenspace_top + self.true_rect.height - title_height - 1

            # If the window goes off this monitor, we need to move the crop back inside the bounds and pad
            if screenspace_left < self.monitor.left:
                pad_left = self.monitor.left - screenspace_left
                screenspace_left = self.monitor.left
            else:
                pad_left = 0
            left = (screenspace_left - self.monitor.left) + x_offset

            if screenspace_top < self.monitor.top:
                pad_top = self.monitor.top - screenspace_top
                screenspace_top = self.monitor.top
            else:
                pad_top = 0
            top = screenspace_top - self.monitor.top

            if screenspace_right > self.monitor.right:
                pad_right = screenspace_right - self.monitor.right
                screenspace_right = self.monitor.right
            else:
                pad_right = 0
            right = screenspace_right - self.monitor.left

            if sceenspace_bottom > self.monitor.bottom:
                pad_bottom = sceenspace_bottom - self.monitor.bottom
                sceenspace_bottom = self.monitor.bottom
            else:
                pad_bottom = 0
            bottom = sceenspace_bottom - self.monitor.top

            width = right - left
            height = bottom - top

            if width <= 0 or height <= 0:
                logger.warning(
                    f"Got invalid crop: {top}:+{height}, {left}:+{width}",
                    exc_info=True)
                return None
            else:
                logger.info(f"Got crop: {top}:+{height}, {left}:+{width}")

            return Crop(
                top=top,
                bottom=bottom,
                left=left,
                right=right,
                pad_top=pad_top,
                pad_bottom=pad_bottom,
                pad_left=pad_left,
                pad_right=pad_right,
            )
Пример #23
0
def get_screen_size():
    """获取缩放后的分辨率"""
    w = win32api.GetSystemMetrics(0)
    h = win32api.GetSystemMetrics(1)
    return w, h
Пример #24
0
import datetime
import random
import sys
import threading
import time
import win32api
import win32con

SCREEN_WIDTH = win32api.GetSystemMetrics(0)
SCREEN_HEIGHT = win32api.GetSystemMetrics(1)


class Mouse_Handler:
    def __init__(self):
        # thread
        self.active_thread = None
        self.timer_handler_thread = None

        # event
        self.timer_countdown = None
        self.movement_delay = None

    def move_mouse(self, ui_input):
        delay = ui_input.delay
        offset = ui_input.offset
        random_movement_enabled = ui_input.random_movement_enabled
        random_delay_enabled = ui_input.random_delay_enabled
        random_movement = ui_input.random_movement
        random_delay = ui_input.random_delay

        random_x_movement_modifier = 0
Пример #25
0
    def grab_fishing_screen(self):
        hwin = win32gui.GetDesktopWindow()

        width = win32api.GetSystemMetrics(win32con.SM_CXVIRTUALSCREEN)
        height = win32api.GetSystemMetrics(win32con.SM_CYVIRTUALSCREEN)
        left = win32api.GetSystemMetrics(win32con.SM_XVIRTUALSCREEN)
        top = win32api.GetSystemMetrics(win32con.SM_YVIRTUALSCREEN)

        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, (left, top), win32con.SRCCOPY)

        signedIntsArray = bmp.GetBitmapBits(True)
        img = np.frombuffer(signedIntsArray, dtype='uint8')
        
        # 4224 is total pixel width
        # 1080 is total monitor height
        img = img.reshape((1080,4224,4))
        
        srcdc.DeleteDC()
        memdc.DeleteDC()
        win32gui.ReleaseDC(hwin, hwindc)
        win32gui.DeleteObject(bmp.GetHandle())
        
        img = cv2.cvtColor(img, cv2.COLOR_BGRA2GRAY)

        # 1280 accounts for left monitor
        img = img[self.yo:self.yu, 1280+self.xl:1280+self.xr]

        # done fishing
        result=cv2.matchTemplate(img,self.donefish,cv2.TM_CCOEFF_NORMED)
        _, max_val, _, _ = cv2.minMaxLoc(result)
        #print("done, when not 1.0: ",max_val)
        if max_val > 0.9:
            #print("fish on screen max_val:",max_val)
            # fish is on screen
            self.done = False

            # reward
            _ , cpimg = cv2.threshold(img, 170, 240, cv2.THRESH_BINARY)
            result=cv2.matchTemplate(cpimg,self.fish,cv2.TM_CCOEFF_NORMED)
            _, max_val, _, _ = cv2.minMaxLoc(result)
            
            #print(max_val)
            if max_val > 0.52:
                self.reward = max_val
            else:
                self.reward = 0

            #cv2.imwrite("test.png", img)
            #sys.exit()

        else:
            self.done = True

        img = img.flatten() 
        return img
Пример #26
0
# -*- coding: utf-8 -*-
import win32api, win32con
import time
from pymouse import PyMouse
from pykeyboard import PyKeyboard

print("程序启动成功,请确认玩课网视频播放页面处于最大化且可见状态。\n")
mouse = PyMouse()
keyboard = PyKeyboard()

x_dim = win32api.GetSystemMetrics(win32con.SM_CXSCREEN)
y_dim = win32api.GetSystemMetrics(win32con.SM_CYSCREEN)
print("屏幕大小获取成功:X轴大小%d, Y轴大小%d。\n" % (x_dim, y_dim))
print("接下来需要确定“下一节”按钮、播放速度调整按钮、二倍速播放按钮的位置。\n")
print("首先确定“下一节”按钮位置,请将鼠标移动到“下一节”按钮上,十秒后程序将自动读取按钮坐标。")
for i in range(0, 10):
    rt = 10 - i
    print("%d" % rt)
    time.sleep(1)
x_click, y_click = mouse.position()
print("已确定“下一节”按钮位置:X轴位置%d, Y轴位置%d。\n" % (int(x_click), int(y_click)))

print("接下来确定播放速度调整按钮位置,请将鼠标移动到播放速度调整按钮按钮上,十秒后程序将自动读取按钮坐标。")
for i in range(0, 10):
    rt = 10 - i
    print("%d" % rt)
    time.sleep(1)
x_double_pre, y_double_pre = mouse.position()
print("已确定播放速度调整按钮位置:X轴位置%d, Y轴位置%d。\n" %
      (int(x_double_pre), int(y_double_pre)))
Пример #27
0
import win32gui
import win32ui
import win32con
import win32api

# grab a handle to the main desktop window
hdesktop = win32gui.GetDesktopWindow()

# determine the size of all monitors in pixeld
width = win32api.GetSystemMetrics(win32con.SM_CXVIRTUALSCREEN)
height = win32api.GetSystemMetrics(win32con.SM_CYVIRTUALSCREEN)
left = win32api.GetSystemMetrics(win32con.SM_XVIRTUALSCREEN)
right = win32api.GetSystemMetrics(win32con.SM_YVIRTUALSCREEN)

# create a device context
desktop_dc = win32gui.GetWindowDC(hdesktop)
img_dc = win32ui.CreateDCFromHandle(desktop_dc)

# create a memory based device context
mem_dc = img_dc.CreateCompatibleDC()

# create a bitmap object
screenshot = win32ui.CreateBitmap()
screenshot.CreateCompatibleBitmap(img_dc, width, height)
mem_dc.SelectObject(screenshot)

# copy the screen into our memory device context
mem_dc.BitBit((0, 0), (width, height), img_dc, (left, top), win32con.SRCCOPY)

# save the bitmap to a file
screenshot.SaveBitmapFile(mem_dc, "c:\\WINDOWS\\Temp\\screenshot.bmp")
Пример #28
0
    #     dlg = win32api.FindWindowEx(hld, None, 'Edit', None)#获取hld下第一个为edit控件的句柄

    buffer = '0' * 50

    len = win32gui.SendMessage(dlg,
                               win32con.WM_GETTEXTLENGTH) + 1  #获取edit控件文本长度

    win32gui.SendMessage(dlg, win32con.WM_GETTEXT, len, buffer)  #读取文本

    print buffer[:len - 1]

    #虚拟鼠标点击按钮(或者回车)

    btnhld = win32gui.FindWindowEx(hld, None, 'Button', None)

    # win32gui.PostMessage(btnhld, win32con.WM_KEYDOWN, win32con.VK_RETURN, 0)

    # win32gui.PostMessage(btnhld, win32con.WM_KEYUP, win32con.VK_RETURN, 0)

    win32gui.PostMessage(btnhld, win32con.WM_LBUTTONDOWN, win32con.MK_LBUTTON,
                         0)

    win32gui.PostMessage(btnhld, win32con.WM_LBUTTONUP, win32con.MK_LBUTTON, 0)

    #获取显示器屏幕大小

    width = win32api.GetSystemMetrics(win32con.SM_CXSCREEN)

    height = win32api.GetSystemMetrics(win32con.SM_CYSCREEN)
    print "width", width
    print "height", height
Пример #29
0
import pyautogui
import os
import time

import win32api
import time

width = win32api.GetSystemMetrics(0)
height = win32api.GetSystemMetrics(1)
midWidth = int((width + 1) / 2)
midHeight = int((height + 1) / 2)

state_left = win32api.GetKeyState(
    0x01)  # Left button down = 0 or 1. Button up = -127 or -128
while True:
    a = win32api.GetKeyState(0x01)
    if a != state_left:  # Button state changed
        state_left = a
        print(a)
        if a < 0:
            print('Left Button Pressed')
        else:
            print('Left Button Released')
            print(pyautogui.position())
            win32api.SetCursorPos((midWidth, midHeight))
    time.sleep(0.001)

# pyautogui.click(589,10)

# pyautogui.click(508,53)
# pyautogui.typewrite("Helloworld")
Пример #30
0
 def screen_width(self):
     return win32api.GetSystemMetrics(0)