Exemplo n.º 1
0
 def highlightGrid(self, event):
     self.mainWindow.hide()
     combat_grid = Grid(env.COMBAT_R, env.VCELLS, env.HCELLS)
     combat_grid.parse()
     self.overlay = GridOverlay(combat_grid)
     self.overlay.highlightEnded.connect(self.mainWindow.show)
     self.overlay.highlight(2)
Exemplo n.º 2
0
 def __init__(self, spell, workdir, name="Fighter"):
     super(Fighter, self).__init__(workdir, name)
     self.spell = spell
     self.fightEndObs = CombatEndObs(self)
     self.fightStartObs = CombatStartObs(self)
     self.grid = Grid(dofus.COMBAT_R, dofus.VCELLS, dofus.HCELLS)
     self.mobs_killed = 0
     self.nbr_fights = 0
Exemplo n.º 3
0
    def test_generate_complete(self):
        grid = Grid(3)
        grid.init_generate_grid()

        # self.assertEqual(len(grid.grid), 36)
        grid.simple_show()
        grid.show_detail()

        grid.check_eliminate()
        for state in grid.direct_states:
            print(state, grid.direct_states[state])
Exemplo n.º 4
0
    def __init__(self, psize, *image):
        """
        Inicializa uma nova instância do objeto.
        :param psize Tamanho dos retalhos.
        :param image Imagens a serem recortadas e manipuladas por retalhos.
        :return PatchWork
        """
        fpsz = float(psize[0]), float(psize[1])

        List.__init__(self, *image)
        Grid.__init__(self, *map(ceil, self.shape / fpsz))

        self.psize = Point(*psize)
Exemplo n.º 5
0
    def __init__(self, psize, *image):
        """
        Inicializa uma nova instância do objeto.
        :param psize Tamanho dos retalhos.
        :param image Imagens a serem recortadas e manipuladas por retalhos.
        :return PatchWork
        """
        fpsz = float(psize[0]), float(psize[1])

        List.__init__(self, *image)
        Grid.__init__(self, *map(ceil, self.shape / fpsz))

        self.psize = Point(*psize)
Exemplo n.º 6
0
def get_grid(grid: str, width: int, height: int) -> Grid:
    match grid:
        case ["colored", _]:
            typer.echo("Using colored grid")
            return ColoredGrid(height, width)
        case ["distance", _]:
            return DistanceGrid(height, width)
        case _:
            return Grid(width, height)
Exemplo n.º 7
0
    def test_check(self):
        grid = Grid(1)
        grid.init_generate_grid()

        grid.show_detail()
        print('数量统计', grid.type_count)

        grid.check_eliminate()

        for state in grid.direct_states:
            print(state, grid.direct_states[state])
Exemplo n.º 8
0
def get_path(matrix_id, s, e):
    grid = Grid(matrix=matrixes[matrix_id])

    s = [x*2-1 for x in s]
    e = [x*2-1 for x in e]

    start = grid.node(*s)
    end = grid.node(*e)

    finder = AStarFinder(diagonal_movement=2)
    path, runs = finder.find_path(start, end, grid)

    #print('operations:', runs, 'path length:', len(path))
    rep = grid.grid_str(path=path, start=start, end=end)
    path2 = [j for i, j in enumerate(path+[e]) if i % 2 == 0]
    #print(path2)
    path3 = []
    #print(s)
    for i, node in enumerate(path2):
        path2[i] = [int((path2[i][0]+1)/2), int((path2[i][1]+1)/2)]
        if i == 0:
            continue
        #print(path2[i-1])
        #print(path2[i])
        path3.append([path2[i][0] - path2[i-1][0], path2[i][1] - path2[i-1][1]])
        #print(i)
        #print(path3)

    #print(path2)
    #print(path3)
    for i, node in enumerate(path3):
        if node == [1, 0]:
            path3[i] = "R"
        elif node == [-1, 0]:
            path3[i] = "L"
        elif node == [0, 1]:
            path3[i] = "D"
        elif node == [0, -1]:
            path3[i] = "U"
        else:
            path3[i] = "X"
    #print(path3)
    #print(" ".join(path3))
    return (" ".join(path3), rep)
Exemplo n.º 9
0
    def test_probably(self):
        grid = Grid(2)
        grid.init_generate_grid()

        grid.simple_show()

        grid.check_eliminate()
        for state in grid.probably_eliminate:
            state_list = grid.probably_eliminate[state]
            for cell in state_list:
                print(cell.direct_type, cell.ref_id, cell.get_pre(grid),
                      cell.indexes, cell.get_next(grid))
Exemplo n.º 10
0
    def test_best_plan(self):
        grid = Grid()
        grid.init_generate_grid()

        grid.show_detail()
        result = grid.swap_by_strategy(StrategyType.HIGH_ORDER_FIRST)

        if len(result) == 0:
            log.error('no swap')
        for i in result:
            log.info('swap %s' % i)
Exemplo n.º 11
0
    def test_get_alternative_monster(self):
        grid = Grid()
        grid.init_generate_grid()

        grid.simple_show()
        # grid.show()

        result = grid.get_complex_swap_choice()
        for vo in result:
            print(vo)

        if len(result) == 0:
            print('There is no way to eliminate it.')
Exemplo n.º 12
0
class Test(unittest.TestCase):

    def setUp(self):
        self.grid = Grid(Palace.XIONGDI)
        self.grid.tian_gan = TianGan.JIA

    def tearDown(self):
        pass

    def testProperties(self):
        self.assertEqual(self.grid.tian_gan, TianGan.JIA, "TianGan mismatch")
        self.assertEqual(self.grid.palace, Palace.XIONGDI, "Palace mismatch")
        self.assertEqual(0, len(self.grid.stars), "List of stars should be initially empty")

    def testStarManipulation(self):
        star_one = Star("one")
        star_two = Star("two")

        # add one star
        self.grid.add_star(star_one)
        self.assertEqual(len(self.grid.stars), 1, "Number of star is incorrect after adding star_one")
        self.assertEqual(self.grid.stars[0], star_one, "List of star is incorrect after adding star_one")

        # adding the same star is a no_op
        self.grid.add_star(star_one)
        self.assertEqual(len(self.grid.stars), 1, "Adding the same star should be a no-op")
        self.assertEqual(self.grid.stars[0], star_one, "Adding the same star should be a no-op")

        # add a second star and verify both stars are in the list via the contain_star API
        self.grid.add_star(star_two)
        self.assertEqual(len(self.grid.stars), 2, "Number of star is incorrect after adding star_two")
        self.assertTrue(self.grid.contain_star(star_one), "Star_one should remain in the list")
        self.assertTrue(self.grid.contain_star(star_two), "Star_two should be added to the list")

        # remove the first star and verify that the correct star is removed
        self.grid.remove_star(star_one)
        self.assertEqual(len(self.grid.stars), 1, "Number of stars is incorrect after removing star_one")
        self.assertEqual(self.grid.stars[0], star_two, "List of star is incorrect after removing star_one")
Exemplo n.º 13
0
    def test_generate(self):
        grid = Grid()
        grid.init_generate_grid()

        self.assertEqual(len(grid.grid), 16)

        for cell in grid.grid:
            log.debug(str(cell))

        log.debug(grid.type_count)

        grid.show_detail()
Exemplo n.º 14
0
def test_creating_grid_assigns_cell_neighbours():
    grid = Grid(2, 2)
    cell = grid[1][1]
    north_cell = cell.north

    assert north_cell
    assert north_cell.row == 0
    assert north_cell.col == 1

    east_cell = cell.east

    assert not east_cell

    south_cell = cell.south

    assert not south_cell

    west_cell = cell.west

    assert west_cell
    assert west_cell.row == 1
    assert west_cell.col == 0
Exemplo n.º 15
0
    def test_swap(self):
        grid = Grid()
        grid.init_generate_grid()

        grid.simple_show()
        result = grid.swap_by_strategy(StrategyType.HIGH_ORDER_FIRST)

        if len(result) == 0:
            log.warning('no swap')
            return
        for i in result:
            log.info('swap %s' % i)
        grid.swap_and_eliminate(result)

        grid.show()
Exemplo n.º 16
0
def test_creating_grid_sets_up_a_2d_grid():
    grid = Grid(2, 2)
    cell = grid[1][1]

    assert cell is not None
Exemplo n.º 17
0
    def test_show(self):
        grid = Grid()
        grid.init_generate_grid()
        grid.show_detail()

        print('数量统计', grid.type_count)
Exemplo n.º 18
0
from core.grid import Grid

if __name__ == "__main__":
    grid = Grid(2, 2)

    image = grid.to_png()
    image.save("results/png_test.png")
Exemplo n.º 19
0
 def test_main_loop(self):
     grid = Grid()
     grid.main_loop(4, StrategyType.HIGH_ORDER_FIRST)
Exemplo n.º 20
0
 def setUp(self):
     self.grid = Grid(Palace.XIONGDI)
     self.grid.tian_gan = TianGan.JIA
Exemplo n.º 21
0
class Fighter(Walker):
    def __init__(self, spell, workdir, name="Fighter"):
        super(Fighter, self).__init__(workdir, name)
        self.spell = spell
        self.fightEndObs = CombatEndObs(self)
        self.fightStartObs = CombatStartObs(self)
        self.grid = Grid(dofus.COMBAT_R, dofus.VCELLS, dofus.HCELLS)
        self.mobs_killed = 0
        self.nbr_fights = 0

    def run(self):
        self.fightStartObs.start()
        self.fightEndObs.start()
        super(Fighter, self).run()

    def onCombatEnded(self):
        self.combatEndReached.set()
        self.combatStarted.clear()
        dofus.COMBAT_ENDED_POPUP_CLOSE_R.click()
        dofus.COMBAT_ENDED_POPUP_R.waitVanish(dofus.COMBAT_ENDED_POPUP_P)
        sleep(0.7)

    def onCombatStarted(self, event):
        match = dofus.LVL_UP_INFO_R.find(dofus.CLOSE_POPUP_P)
        if match:
            match.click()
        try:
            logging.info("Combat started")
            self.combatStarted.set()
            self.combatEndReached.clear()
            self.combatEnded.clear()
            self.dead = False
            if event == 'combat':
                pyautogui.press(dofus.SKIP_TURN_SHORTCUT)
            dofus.OUT_OF_COMBAT_R.hover()
            self.combatAlgo()
            sleep(10)
            self.combatEnded.set()
            self.nbr_fights += 1
            logging.debug('Combat ended')
        except Exception:
            logging.error("Fatal error in main run!", exc_info=True)
            self.interrupt()
        logging.info(f"I farmed {self.nbr_fights} fights")
        logging.info('Goodbye cruel world.')

    def waitTurn(self, rate=3, timeout=60 * 2):
        """
        Waits for bot turn.
        :param timeout: timeout in seconds
        :param rate: scan rate
        """
        s = perf_counter()
        while not self.killsig.is_set() and\
                not self.combatEndReached.is_set() and\
                perf_counter() - s < timeout:
            s = perf_counter()
            if self.myTurn():
                logging.debug('Bot turn started')
                return True
            elapsed = perf_counter() - s
            sleep((1 / rate) - elapsed)
        raise WaitTurnTimedOut

    def interrupt(self):
        """
        interrupt thread.
        """
        dofus.READY_R.stopWait.set()
        self.combatEnded.set()
        super(Fighter, self).interrupt()

    def combatAlgo(self):
        nbr_errors = 0
        self.mobs_killed = 0
        while not self.combatEndReached.wait(1):
            self.checkCreatureMode()
            try:
                if not self.myTurn():
                    self.waitTurn()
                self.playTurn()
                nbr_errors = 0
            except (FindPathFailed, ParseGridFailed, MoveToCellFailed,
                    UseSpellFailed, WaitTurnTimedOut) as e:
                if self.combatEndReached.is_set() or self.killsig.is_set():
                    return True
                if self.disconnected.is_set():
                    self.connected.wait()
                elif dofus.COMBAT_R.find(dofus.REDUCE_BOX_P):
                    dofus.COMBAT_R.find(dofus.REDUCE_BOX_P).click()
                else:
                    logging.error(str(e), exc_info=True)
                    nbr_errors += 1
                    logging.debug(
                        f"Will skip bots turn for the '{nbr_errors}'th time!")
                    if nbr_errors == 10:
                        logging.debug(
                            "Reached maximum of turns skip on error. Will resign combat."
                        )
                        self.dead = True
                        self.resign()
                        return False
            self.skipTurn()

    @staticmethod
    def skipTurn():
        pyautogui.press(dofus.SKIP_TURN_SHORTCUT)

    @staticmethod
    def myTurn():
        return dofus.MY_TURN_CHECK_L.getpixel() == dofus.MY_TURN_C

    def playTurn(self):
        """
        Play turn loop
        """
        usedSpells = 0
        while not self.combatEndReached.wait(
                3) and usedSpells < self.spell['nbr']:
            self.parseCombatGrid()
            if not self.mobs_killed:
                self.mobs_killed = len(self.grid.mobs)
            if self.combatEndReached.wait(0.5):
                return
            mob, path = self.findPathToTarget(self.grid.bot,
                                              self.spell['range'],
                                              self.grid.mobs)
            if not mob:
                mob, path = self.findPathToTarget(self.grid.bot,
                                                  self.spell['range'],
                                                  self.grid.invoke)
            if not mob:
                raise FindPathFailed(self.grid)
            if path:
                cell = self.cellToTarget(path)
                if cell:
                    self.moveToCell(cell)
                    if cell == path[-1]:
                        if self.combatEndReached.wait(0.5):
                            return
                        self.useSpell(self.spell, mob)
                    else:
                        break
            else:
                self.useSpell(self.spell, mob)
            usedSpells += 1

    def parseCombatGrid(self, timeout=5):
        """
        Parse combat grid.
        :param timeout:  time out in seconds
        :return: True if all good else raise ParseGridFailed
        """
        s = perf_counter()
        while not self.killsig.is_set() and\
                not self.combatEndReached.is_set() and\
                perf_counter() - s < timeout:
            if self.grid.parse():
                return True

    @staticmethod
    def cellToTarget(path):
        """
        Get nearest reachable cell to target
        :param path: path to targeted cell
        :return: Reachable cell if any else None
        """
        if path[-1].reachable():
            return path[-1]
        for idx, cell in enumerate(path):
            if not cell.reachable():
                if idx == 0:
                    return None
                return path[idx - 1]
        return None

    def moveToCell(self, cell, timeout=10):
        """
        Move to a target cell.
        :param cell: cell object
        :param timeout: time out in seconds
        :return: True if all good else raise MoveToCellFailed
        """
        s = perf_counter()
        while not self.killsig.is_set() and \
                not self.combatEndReached.is_set() and \
                perf_counter() - s < timeout:
            cell.click()
            dofus.OUT_OF_COMBAT_R.hover()
            if cell.waitAppear(dofus.ObjType.BOT, 1):
                return True
        raise MoveToCellFailed(cell)

    @staticmethod
    def useSpell(spell, target, timeout=5):
        """
        Cast given spell on the target
        :param spell: spell dictionary
        :param target: targeted cell
        :param timeout: time out in seconds
        :return: True if all good else raise UseSpellFailed
        """
        pyautogui.press(spell['shortcut'])
        target.click()
        dofus.OUT_OF_COMBAT_R.hover()
        if target.waitAnimation(timeout):
            return True

        raise UseSpellFailed(target)

    def findPathToTarget(self, start_cell, po, targets):
        """
        Find path to the closest ldv to hit a mob.
        :param start_cell: position of the character
        :param po: range of the ldv
        :param targets: positions of the mobs
        :return: cell of the mob, path to the ldv if any else None
        """
        logging.debug("searching path to mobs")
        queue = collections.deque([[start_cell]])
        seen = {start_cell.indexes()}
        while not self.killsig.is_set() and not self.combatEndReached.is_set(
        ) and queue:
            path = queue.popleft()
            curr = path[-1]
            for mob in targets:
                if curr.inLDV(mob, po):
                    return mob, path[1:]
            for cell in curr.neighbors():
                if (cell.i, cell.j) not in seen and not cell.occupied():
                    queue.append(path + [cell])
                    seen.add(cell.indexes())
        return None, None

    @staticmethod
    def checkCreatureMode():
        """
        Check creature mode at the start of the fight if its not checked.
        """
        if dofus.CREATURE_MODE_R.find(dofus.CREATURE_MODE_OFF_P,
                                      grayscale=False):
            dofus.CREATURE_MODE_R.click()
            dofus.OUT_OF_COMBAT_R.hover()

    def harvestCombats(self, mobs_patterns, max_tries=10, shuffle=False):
        """
        Look for mobs patterns and try to enter combats.
        :param mobs_patterns: list of images
        :param max_tries: max number of clicks on mobs group
        :param shuffle: if you want to shuffle mobs patterns before matching
        :return: nbr of mobs farmed and the matched patterns with nbr of times matched
        """
        nbr_fails = 0
        result = {"farmed": 0, "matched": {}}
        while not self.killsig.is_set() and nbr_fails < max_tries:
            logging.debug("Searching for mobs group...")
            tgt, idx = dofus.COMBAT_R.findAny(mobs_patterns,
                                              threshold=0.8,
                                              shuffle=shuffle)
            if tgt:
                logging.debug("I found a mob group")
                if self.enterCombat(tgt):
                    nbr_fails = 0
                    if idx not in result['matched']:
                        result['matched'][idx] = 0
                    result['matched'][idx] += 1
                    self.combatEnded.wait()
                    result["farmed"] += self.mobs_killed
                    if self.dead:
                        logging.debug("Walker dead during combat!")
                        break
                else:
                    nbr_fails += 1
            else:
                logging.debug("No mobs found")
                break
        return result

    def enterCombat(self, tgt, timeout=3.5):
        """
        Click on a mob group and wait for the combat to start.
        :param tgt: pos of mobs group in the screen
        :param timeout: timeout in seconds
        :return: True if all good else False
        """
        tgt.click()
        logging.debug("Clicked on mobs group")
        s = perf_counter()
        if self.combatStarted.wait(timeout):
            logging.debug(f"Enter combat took: {perf_counter() - s}")
            return True
        logging.debug("Couldn't open combat!")
        return False

    @staticmethod
    def resign():
        """
        Abandon combat.
        """
        dofus.RESIGN_BUTTON_LOC.click()
        dofus.RESIGN_POPUP_R.waitAppear(dofus.RESIGN_POPUP_P)
        dofus.RESIGN_CONFIRM_L.click()
        dofus.RESIGN_POPUP_R.waitVanish(dofus.RESIGN_POPUP_P)
        dofus.DEFEAT_POPUP_R.waitAppear(dofus.DEFEAT_POPUP_P)
        dofus.DEFEAT_POPUP_CLOSE_L.click()
        dofus.DEFEAT_POPUP_R.waitVanish(dofus.DEFEAT_POPUP_P)
Exemplo n.º 22
0
from generators.binary_tree import BinaryTree
from core.grid import Grid

if __name__ == "__main__":
    grid = Grid(10, 10)
    BinaryTree.on(grid)

    print(grid)
    image = grid.to_png()

    image.save("results/binary_tree.png")
Exemplo n.º 23
0
def test_iterating_over_grid_goes_column_first():
    grid = Grid(2, 2)
    cells = [cell for cell in grid]

    assert len(cells) == 4
    assert cells[1].row == 0 and cells[1].col == 1