跳到正文

剪贴板

剪贴板 7ofj2dyw

原文
剪贴板信息

剪贴板信息

收录
更新

以下均为本人亲自所写,不得未经允许或未经备注使用!

Python
import collections
import random
import pyautogui
import pytesseract
import pyscreeze
import threading
import numpy as np
import keyboard
import signal
import time
import os
import math
import cv2

class Constants:
    SCREENSHOT_LOCATION = 'screenshot.png'
    MAP_LOCATION = 'map.png'
    XP_LOCATION = 'xp.png'
    DEBUGGING = True
    IMG_LEN = 300
    ERR = 2147483647
    MOVE_LEN = 8
    DIST_XP_RATIO = 100  # TODO: tweak parameters
    ROTATING_SPEED = 0.75


class Utils:
    @staticmethod
    def distance_squared(point1, point2):
        return (point1[0] - point2[0]) * (point1[0] - point2[0]) + \
            (point1[1] - point2[1]) * (point1[1] - point2[1])

    @staticmethod
    def mse(arr1, arr2):
        if len(arr1) != len(arr2):
            print("MSE function parameters has different lengths!")
            raise Exception
        cnt = 0
        for i in range(len(arr1)):
            cnt += (arr1[i] - arr2[i]) * (arr1[i] - arr2[i])
        return cnt

    @staticmethod
    def mse_image(img1, img2):
        h1, w1 = img1.shape
        h2, w2 = img2.shape
        if h1 != h2 or w1 != w2:
            print("Two images does not have same size!")
            raise Exception
        count = 0
        for i in range(h1):
            for j in range(w1):
                pixel1 = img1[i][j]
                pixel2 = img2[i][j]
                count += Utils.mse(pixel1, pixel2)
        count /= (h1 * w1)
        return count

    @staticmethod
    def close_to(color1, color2, sum_diff=1000):
        return Utils.mse(color1, color2) <= sum_diff

    @staticmethod
    def is_grey_or_white(color):
        return 0.8 < color[0] / color[1] < 1.2 and 0.8 < color[1] / color[2] < 1.2

    @staticmethod
    def get_rad_by_coord(x, y):
        rad = math.atan(y / x)
        if x < 0:
            rad += math.pi
        return (rad + math.pi * 2) % (math.pi * 2)

class Bubbler:
    last_time_since_checked = time.time_ns() // 1000000  # Milliseconds since epoch
    last_bubble_rad = 0
    is_update = True
    is_clockwise = True
    pressed_shift = False

    @staticmethod
    def stop_updating():
        Bubbler.is_update = False

    @staticmethod
    def update_bubble_rad():
        bubble_img = cv2.imread("Images/Bubble.PNG")
        not_found_bubble = True
        sum_rad, num_rad = 0, 0
        while not_found_bubble:
            sum_rad, num_rad = 0, 0
            flower = (960, 593)
            radius = 40
            screenshot = Images.get_screenshot()[flower[1] - radius:flower[1] + radius,
                                                 flower[0] - radius:flower[0] + radius]
            bubble_list = []
            for bubble in pyautogui.locateAll(bubble_img, screenshot, confidence=0.7):
                coord = pyautogui.center(bubble)
                is_new_bubble = True
                for prev_bubble in bubble_list:
                    if Utils.distance_squared(coord, (prev_bubble[0] / prev_bubble[2], prev_bubble[1] / prev_bubble[2])) <= 50:
                        prev_bubble[0] += coord.x
                        prev_bubble[1] += coord.y
                        prev_bubble[2] += 1
                        is_new_bubble = False
                        break
                if is_new_bubble:
                    bubble_list.append([coord.x, coord.y, 1])
            if len(bubble_list) > 0:
                not_found_bubble = False
            for bubble in bubble_list:
                coord = (bubble[0] / bubble[2], bubble[1] / bubble[2])
                rad = Utils.get_rad_by_coord(coord[0] - radius, radius - coord[1])
                # Since y is reversed in computer coordinates
                sum_rad += rad
                num_rad += 1
        Bubbler.last_bubble_rad = sum_rad / num_rad
        print("Current bubble radians:", Bubbler.last_bubble_rad)
        Bubbler.last_time_since_checked = time.time_ns() / 1000000000

    @staticmethod
    def update_clockwise_rotation():
        img = Images.get_screenshot()[925:995, 565:635]
        yin_yang = cv2.imread("Images/Petals/MYinYang.PNG")
        Bubbler.is_clockwise = (Utils.mse_image(img, yin_yang) > 1000)

    @staticmethod
    def forever_update_bubble_rad():
        while Bubbler.is_update:
            Bubbler.update_bubble_rad()
            Bubbler.update_clockwise_rotation()

    @staticmethod
    def get_rad():
        return (Bubbler.last_bubble_rad + math.pi + Constants.ROTATING_SPEED * (
                time.time_ns() / 1000000000 - Bubbler.last_time_since_checked)) % math.pi

    @staticmethod
    def auto_bubble_with_keyboard():
        rad = Bubbler.get_rad()
        epsilon = math.pi / 9
        move_to_rad = {'a': 0, 's': math.pi / 2, 'd': math.pi, 'w': math.pi * 3 / 2}
        goal_rad = move_to_rad[Florr.get_last_move()]
        if goal_rad == 0:
            is_bubble = (math.pi - epsilon <= rad or rad <= epsilon)
        else:
            is_bubble = (goal_rad - epsilon <= rad <= goal_rad + epsilon)
        if is_bubble:
            if not Bubbler.pressed_shift:
                Bubbler.pressed_shift = True
                pyautogui.keyDown("shift")
                if Constants.DEBUGGING:
                    print("shift")
            if goal_rad == 0:
                if (math.pi - epsilon <= rad and Bubbler.is_clockwise) or (
                        rad <= epsilon and not Bubbler.is_clockwise):
                    pyautogui.keyDown("1")
                    if Constants.DEBUGGING:
                        print(1)
                    Bubbler.is_clockwise = not Bubbler.is_clockwise
                    time.sleep(random.random() / 80 + 0.04)  # 0.04 to 0.0525
                    pyautogui.keyUp("1")
            else:
                if (goal_rad - epsilon <= rad <= goal_rad and Bubbler.is_clockwise) or \
                        (goal_rad <= rad <= goal_rad + epsilon and not Bubbler.is_clockwise):
                    pyautogui.keyDown("1")
                    if Constants.DEBUGGING:
                        print(1)
                    Bubbler.is_clockwise = not Bubbler.is_clockwise
                    time.sleep(random.random() / 80 + 0.04)  # 0.04 to 0.0525
                    pyautogui.keyUp("1")
        else:
            if Bubbler.pressed_shift:
                Bubbler.pressed_shift = False
                pyautogui.keyUp("shift")
                if Constants.DEBUGGING:
                    print("unshift")

class Images:
    @staticmethod
    def get_screenshot():
        # Complexity: 28ms
        # pyautogui.screenshot(Constants.SCREENSHOT_LOCATION)
        # return cv2.imread(Constants.SCREENSHOT_LOCATION)
        return cv2.imread(Constants.SCREENSHOT_LOCATION)  # TODO: change back

    @staticmethod
    def get_map():
        # Complexity: 28ms
        return Images.get_screenshot()[130:430, 1600:1900]  # (y, x)

    @staticmethod
    def get_xp_line():
        # Complexity: 28ms
        xp_line = Images.get_screenshot()[242:255, 126:265]
        empty = np.array([14, 25, 4])
        h, w = xp_line.shape[:2]
        for y in range(0, h):
            for x in range(0, w):
                pixel = xp_line[y][x]
                if not Utils.is_grey_or_white(pixel):
                    xp_line[y][x] = empty
        return xp_line

class Florr:
    last_move = ""
    dist = np.full((Constants.IMG_LEN, Constants.IMG_LEN), Constants.ERR, dtype=int)

    @staticmethod
    def get_last_move():
        return Florr.last_move

    @staticmethod
    def get_current_location():
        # Complexity: 317ms
        florr_map = Images.get_map()
        h, w = florr_map.shape[:2]
        self_color = np.array([75, 222, 188])
        sumx, numx, sumy, numy = 0, 0, 0, 0
        for y in range(0, h):
            for x in range(0, w):
                pixel = florr_map[y][x]
                if Utils.close_to(pixel, self_color):
                    sumx += x
                    sumy += y
                    numx += 1
                    numy += 1
        if numx == 0 or numy == 0:
            print("Flower self not found in map!")
            raise Exception
        avg_x, avg_y = round(sumx / numx), round(sumy / numy)
        if Constants.DEBUGGING:
            print("Flower coordinates:", avg_x, avg_y)
        return avg_x, avg_y

    @staticmethod
    def get_xp():
        # Complexity: 228ms
        xp_line = Images.get_xp_line()
        if Constants.DEBUGGING:
            cv2.imwrite(Constants.XP_LOCATION, xp_line)
        text = pytesseract.image_to_string(xp_line, config='--psm 7 -c tessedit_char_whitelist=0123456789/kmbXP')
        xp = ""
        for char in text:
            if char != '/':
                xp += char
            else:
                break
        if Constants.DEBUGGING:
            print("XP:", int(xp))
        return int(xp)

    @staticmethod
    def get_reward():
        # Complexity: 544ms
        # Calculate Distance Reward
        location = Florr.get_current_location()
        distance = Florr.dist[location[0]][location[1]]
        # Calculate XP Reward
        xp = Florr.get_xp()
        if Constants.DEBUGGING:
            print("Distance:", distance)
        return Constants.DIST_XP_RATIO * distance + int(xp)

    @staticmethod
    def is_death():
        pass  # TODO: implement

    @staticmethod
    def visualize_distance():
        # Complexity: 315ms
        florr_map = Images.get_map()
        max_dist = 0
        for i in range(Constants.IMG_LEN):
            for j in range(Constants.IMG_LEN):
                if Florr.dist[i][j] != Constants.ERR:
                    max_dist = max(max_dist, Florr.dist[i][j])
        ratio = max_dist / 230
        if Constants.DEBUGGING:
            print("Maximum Distance:", max_dist)
        for i in range(0, Constants.IMG_LEN):
            for j in range(0, Constants.IMG_LEN):
                if Florr.dist[i][j] == Constants.ERR:
                    florr_map[j][i] = np.array([0, 0, 0])
                else:
                    florr_map[j][i] = np.array([Florr.dist[i][j] / ratio + 25, Florr.dist[i][j] / ratio + 25,
                                                Florr.dist[i][j] / ratio + 25])
        cv2.imshow("Pic", florr_map)
        cv2.waitKey(0)

    @staticmethod
    def get_origin():
        # garden_map = cv2.imread("GardenMap.PNG")
        # desert_map = cv2.imread("DesertMap.PNG")
        # ocean_map = cv2.imread("OceanMap.PNG")
        # jungle_map = cv2.imread("JungleMap.PNG")
        # ant_hell_map = cv2.imread("AntHellMap.PNG")
        # sewer_map = cv2.imread("SewerMap.PNG")
        # hel_map = cv2.imread("HelMap.PNG")
        # map_list = [garden_map, desert_map, ocean_map, jungle_map, ant_hell_map, sewer_map, hel_map]
        # florr_map = get_map()
        # current_map_index = -1
        # for index, biome_map in enumerate(map_list):
        #     if mse_image(florr_map, biome_map) <= 2000:
        #         current_map_index = index
        #         break
        # if current_map_index == -1:
        #     print("Current map not found!")
        #     raise Exception
        # origin = [(72, 144), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0)]
        # return origin[current_map_index]
        return 72, 144  # TODO: Do casework on current biome

    @staticmethod
    def init_distance_matrix():
        # Complexity: 685ms
        florr_map = Images.get_map()
        h, w = florr_map.shape[:2]
        self_color = np.array([75, 222, 188])
        white = np.array([231, 242, 221])
        for y in range(0, h):
            for x in range(0, w):
                pixel = florr_map[y][x]
                if Utils.close_to(pixel, self_color):
                    florr_map[y][x] = white
        origin = Florr.get_origin()
        q = collections.deque()
        q.append(origin)
        Florr.dist[origin[0]][origin[1]] = 0
        first_iteration = True
        while len(q) > 0:
            coord = q.popleft()
            if not first_iteration:
                if Florr.dist[coord[0]][coord[1]] != Constants.ERR:
                    continue
                if not Utils.close_to(florr_map[coord[1]][coord[0]], white):
                    continue
                Florr.dist[coord[0]][coord[1]] = min(Florr.dist[coord[0] + 1][coord[1]],
                                                     Florr.dist[coord[0] - 1][coord[1]],
                                                     Florr.dist[coord[0]][coord[1] + 1],
                                                     Florr.dist[coord[0]][coord[1] - 1],
                                                     Florr.dist[coord[0] - 1][coord[1] - 1],
                                                     Florr.dist[coord[0] - 1][coord[1] + 1],
                                                     Florr.dist[coord[0] + 1][coord[1] - 1],
                                                     Florr.dist[coord[0] + 1][coord[1] + 1]) + 1
            q.append((coord[0] + 1, coord[1]))
            q.append((coord[0] - 1, coord[1]))
            q.append((coord[0], coord[1] + 1))
            q.append((coord[0], coord[1] - 1))
            q.append((coord[0] - 1, coord[1] - 1))
            q.append((coord[0] - 1, coord[1] + 1))
            q.append((coord[0] + 1, coord[1] - 1))
            q.append((coord[0] + 1, coord[1] + 1))
            first_iteration = False

    @staticmethod
    def move():
        coord = Florr.get_current_location()
        new_coords = [(coord[0] + Constants.MOVE_LEN, coord[1]), (coord[0] - Constants.MOVE_LEN, coord[1]),
                      (coord[0], coord[1] + Constants.MOVE_LEN), (coord[0], coord[1] - Constants.MOVE_LEN)]
        new_movements = ['d', 'a', 's', 'w']
        max_dist, max_index = 0, 0
        for index, new_coord in enumerate(new_coords):
            new_dist = Florr.dist[new_coord[0]][new_coord[1]]
            if new_dist > max_dist and new_dist != Constants.ERR:
                max_dist = new_dist
                max_index = index
        choice = new_movements[max_index]
        if Florr.last_move != choice:
            if Florr.last_move != "":
                pyautogui.keyUp(Florr.last_move)
            pyautogui.keyDown(choice)
        Florr.last_move = choice

if __name__ == "__main__":
    pyscreeze.USE_IMAGE_NOT_FOUND_EXCEPTION = False
    pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'
    Florr.init_distance_matrix()
    # time.sleep(3)
    Bubbler.update_bubble_rad()
    while not keyboard.is_pressed('v'):
        Florr.move()
        Bubbler.update_bubble_rad()
        print(Bubbler.is_clockwise, Bubbler.last_bubble_rad, Bubbler.last_time_since_checked)
        Bubbler.update_clockwise_rotation()

        Bubbler.auto_bubble_with_keyboard()
    Bubbler.stop_updating()
    pid = os.getpid()
    os.kill(pid, signal.SIGTERM)