コード例 #1
0
def jhudora_quest():
    np = NeoPage(save_pages=True)
    np.get(path)

    if 'I Accept!' in np.content:
        # TODO: Search your SDB, gallery, shop, and Neohome Superstore for item as well.
        user = os.environ['NP_USER']
        np.post(path_process, 'type=accept', f'username={user}')
        m = re.search(
            r"<br>Where is my <b>(.*?)</b>\?<p><img src='http://images.neopets.com/items/(.*?)'.*?>",
            np.content)
        item = m[1]
        image = m[2]
        print(f'Jhudora asked for {item} ({image})')
        cost = inventory.purchase(item, image=image)
        print(f'Bought it for {cost} NP.')
        np.set_referer_path(path)
        np.post(path_process, 'type=finished')
        if 'You have completed' in np.content:
            print(f'Quest shouuuuld be completed?')
        else:
            print(f"Quest doesn't seem to have completed")
    elif 'I am not ready' in np.content:
        print("Too early for Jhudora's Quest.")
    else:
        print("Jhudora's quest: Error!")
コード例 #2
0
def goto_level(lvl):
    np = NeoPage()
    #np.set_referer_path(path_game)
    #np.post(path_process, 'type=reset_this_thing', 'username={os.environ["NP_USER"]}')
    #print(np.last_file_path)

    #if shapeshifter(timeout=0) == 2:
    #    print('Shapeshifter: Already done.')
    #    return

    np.set_referer_path(path_game)
    np.post(path_process + '?type=init', f'past_level={lvl}')
    print(np.last_file_path)
コード例 #3
0
ファイル: shapeshifter.py プロジェクト: neynt/nptools
def goto_level(lvl):
    np = NeoPage()
    #np.set_referer_path(path_game)
    #np.post(path_process, 'type=reset_this_thing', 'username={os.environ["NP_USER"]}')
    #print(np.last_file_path)

    #if shapeshifter(timeout=0) == 2:
    #    print('Shapeshifter: Already done.')
    #    return

    np.set_referer_path(path_game)
    np.post(path_process + '?type=init', f'past_level={lvl}')
    print(np.last_file_path)
コード例 #4
0
ファイル: jhudora_quest.py プロジェクト: neynt/nptools
def jhudora_quest():
    np = NeoPage(save_pages=True)
    np.get(path)

    if 'I Accept!' in np.content:
        # TODO: Search your SDB, gallery, shop, and Neohome Superstore for item as well.
        user = os.environ['NP_USER']
        np.post(path_process, 'type=accept', f'username={user}')
        m = re.search(r"<br>Where is my <b>(.*?)</b>\?<p><img src='http://images.neopets.com/items/(.*?)'.*?>", np.content)
        item = m[1]
        image = m[2]
        print(f'Jhudora asked for {item} ({image})')
        cost = inventory.purchase(item, image=image)
        print(f'Bought it for {cost} NP.')
        np.set_referer_path(path)
        np.post(path_process, 'type=finished')
        if 'You have completed' in np.content:
            print(f'Quest shouuuuld be completed?')
        else:
            print(f"Quest doesn't seem to have completed")
    elif 'I am not ready' in np.content:
        print("Too early for Jhudora's Quest.")
    else:
        print("Jhudora's quest: Error!")
コード例 #5
0
def shapeshifter(timeout=10 * 60):
    np = NeoPage()
    np.get(path_index)
    starting_np = np.current_np()
    if np.contains('Continue Game!'):
        np.get(path_game)
    elif np.contains('Start Game!'):
        np.post(path_process, f'type=init')

    # Just in case we won but left it in the completed state
    if np.contains('You Won!') or np.contains('You Lost!'):
        np.post(path_process + '?type=init')

    tbl = np.search(r'''<table border=1 bordercolor='gray'>(.*?)</table>''')[1]
    imgs = re.findall(
        r'''<img src='(.*?)' border=0 name='i_'>(<br><b><small>GOAL</small></b></td>)?''',
        tbl)
    imgs = imgs[:-1]
    N = len(imgs)
    goal_idx = next(i for i, (_, goal) in enumerate(imgs) if goal)
    to_idx = {img: i for i, (img, _) in enumerate(imgs)}

    tbl = np.search(
        r'''<table align=center cellpadding=0 cellspacing=0 border=0>(.*?)</table>'''
    )[1]
    goal_grid = []
    for row in re.findall(r'''<tr>(.*?)</tr>''', tbl, flags=re.DOTALL):
        imgs = re.findall(r'''<img src='(.*?)' .*?>''', row)
        goal_row = [to_idx[img] for img in imgs]
        goal_grid.append(goal_row)

    tbl = np.search(
        r'''<center><b><big>ACTIVE SHAPE</big></b><p>(.*?)</table>\n''')[1]
    shape_grids = []
    for shape_info in re.findall(r'''<table.*?>(.*?)</table>''', tbl):
        grid = []
        for row_info in re.findall(r'''<tr>(.*?)</tr>''', shape_info):
            tiles = re.findall(r'''<td.*?>(.*?)</td>''', row_info)
            grid.append(
                [int('square.gif' in tile_info) for tile_info in tiles])
        shape_grids.append(grid)

    # Compute kvho difficulty.
    R = len(goal_grid)
    C = len(goal_grid[0])
    min_shifts_needed = R * C * (N - 1) - sum(map(sum, goal_grid))
    shifts_available = sum(
        sum(sum(rows) for rows in grid) for grid in shape_grids)
    num_overshifts = shifts_available - min_shifts_needed
    num_flips = num_overshifts // N
    print(f'Puzzle permits {num_flips} flips ({num_overshifts} overshifts)')

    kvho_input = make_kvho_input(goal_grid, shape_grids, goal_idx)

    print(f'Waiting for kvho.')
    start_time = datetime.now()

    positions = []
    try:
        proc = subprocess.run(['c/ss'],
                              input=kvho_input,
                              encoding='utf-8',
                              capture_output=True,
                              timeout=timeout)
        for line in proc.stdout.splitlines():
            if 'x' in line and '=' in line:
                x = list(
                    map(
                        int,
                        line.replace('x', ' ').replace('=',
                                                       ' ').strip().split()))
                for c, r, _ in zip(x[::3], x[1::3], x[2::3]):
                    positions.append((r, c))
        print(f'Solution found in {datetime.now() - start_time}: {positions}')
    except subprocess.TimeoutExpired:
        print(
            f'Solution not found in time. Throwing this puzzle to get a new one.'
        )
        for _ in shape_grids:
            positions.append((0, 0))

    for i, (shape, (r, c)) in enumerate(zip(shape_grids, positions)):
        print(f'\rPlacing piece {i+1}/{len(positions)}', end='')
        np.set_referer_path(path_game)
        np.get(path_process, 'type=action', f'posx={c}', f'posy={r}')
        time.sleep(0.5)
    print()

    if np.contains('You Won!'):
        np.set_referer_path(path_game)
        np.post(path_process + '?type=init')
        ending_np = np.current_np()
        print(f'Done level, earned {ending_np - starting_np} NP')
        return 1
    elif np.contains('reached your max neopoints'):
        print('Done for today.')
        return 2
    else:
        print('Did not solve level??')
        return 0
コード例 #6
0
ファイル: shapeshifter.py プロジェクト: neynt/nptools
def shapeshifter(timeout=10*60):
    np = NeoPage()
    np.get(path_index)
    starting_np = np.current_np()
    if np.contains('Continue Game!'):
        np.get(path_game)
    elif np.contains('Start Game!'):
        np.post(path_process, f'type=init')

    # Just in case we won but left it in the completed state
    if np.contains('You Won!') or np.contains('You Lost!'):
        np.post(path_process + '?type=init')

    tbl = np.search(r'''<table border=1 bordercolor='gray'>(.*?)</table>''')[1]
    imgs = re.findall(r'''<img src='(.*?)' border=0 name='i_'>(<br><b><small>GOAL</small></b></td>)?''', tbl)
    imgs = imgs[:-1]
    N = len(imgs)
    goal_idx = next(i for i, (_, goal) in enumerate(imgs) if goal)
    to_idx = {img: i for i, (img, _) in enumerate(imgs)}

    tbl = np.search(r'''<table align=center cellpadding=0 cellspacing=0 border=0>(.*?)</table>''')[1]
    goal_grid = []
    for row in re.findall(r'''<tr>(.*?)</tr>''', tbl, flags=re.DOTALL):
        imgs = re.findall(r'''<img src='(.*?)' .*?>''', row)
        goal_row = [to_idx[img] for img in imgs]
        goal_grid.append(goal_row)

    tbl = np.search(r'''<center><b><big>ACTIVE SHAPE</big></b><p>(.*?)</table>\n''')[1]
    shape_grids = []
    for shape_info in re.findall(r'''<table.*?>(.*?)</table>''', tbl):
        grid = []
        for row_info in re.findall(r'''<tr>(.*?)</tr>''', shape_info):
            tiles = re.findall(r'''<td.*?>(.*?)</td>''', row_info)
            grid.append([int('square.gif' in tile_info) for tile_info in tiles])
        shape_grids.append(grid)

    # Compute kvho difficulty.
    R = len(goal_grid)
    C = len(goal_grid[0])
    min_shifts_needed = R * C * (N - 1) - sum(map(sum, goal_grid))
    shifts_available = sum(sum(sum(rows) for rows in grid) for grid in shape_grids)
    num_overshifts = shifts_available - min_shifts_needed
    num_flips = num_overshifts // N
    print(f'Puzzle permits {num_flips} flips ({num_overshifts} overshifts)')

    kvho_input = make_kvho_input(goal_grid, shape_grids, goal_idx)

    print(f'Waiting for kvho.')
    start_time = datetime.now()

    positions = []
    try:
        proc = subprocess.run(['c/ss'], input=kvho_input, encoding='utf-8', capture_output=True, timeout=timeout)
        for line in proc.stdout.splitlines():
            if 'x' in line and '=' in line:
                x = list(map(int, line.replace('x', ' ').replace('=', ' ').strip().split()))
                for c, r, _ in zip(x[::3], x[1::3], x[2::3]):
                    positions.append((r, c))
        print(f'Solution found in {datetime.now() - start_time}: {positions}')
    except subprocess.TimeoutExpired:
        print(f'Solution not found in time. Throwing this puzzle to get a new one.')
        for _ in shape_grids:
            positions.append((0, 0))

    for i, (shape, (r, c)) in enumerate(zip(shape_grids, positions)):
        print(f'\rPlacing piece {i+1}/{len(positions)}', end='')
        np.set_referer_path(path_game)
        np.get(path_process, 'type=action', f'posx={c}', f'posy={r}')
        time.sleep(0.5)
    print()

    if np.contains('You Won!'):
        np.set_referer_path(path_game)
        np.post(path_process + '?type=init')
        ending_np = np.current_np()
        print(f'Done level, earned {ending_np - starting_np} NP')
        return 1
    elif np.contains('reached your max neopoints'):
        print('Done for today.')
        return 2
    else:
        print('Did not solve level??')
        return 0
コード例 #7
0
ファイル: battledome.py プロジェクト: andrew-db/nptools
def battledome(forever=False):
    np = NeoPage(path)
    np.get(path_arena)
    neopoints_left = True
    prizes_left = True
    while prizes_left or forever:
        battle_id = None
        if np.contains('battleid:'):
            print('Battledome: Already in fight.')
            battle_id = np.search(r"battleid:'(\d+)',")[1]
        else:
            print('Battledome: Starting fight.')
            np.post(path_start_fight, 'type=2', f'pet={PET_NAME}',
                    f'npcId={npc_id}', f'toughness={toughness}')
            battle = json.loads(np.content)
            if not battle['success']:
                print('Battledome: Error.')
                return
            battle_id = battle['battle']['id']
        time.sleep(2)
        np.set_referer_path(path)
        np.get(path_arena)
        ts = int(time.time() * 1000)
        for step in itertools.count():
            intro = 1 if step == 0 else 0
            np.set_referer_path(path_arena)
            np.post(path_arena_ajax, f'battleid={battle_id}', f'step={step}',
                    f'intro={intro}', 'status=1')
            resp = json.loads(np.content)
            abils = resp['p1']['abils']
            chosen_abil = ''
            for abil in ['21', '2', '14', '17', '1']:
                if abil in abils and not abils[abil]['hasCooldown']:
                    chosen_abil = abil
                    break
            items = re.findall(
                r'<li><img.*?id="(\d+)".*?title="(.*?)".*?/></li>',
                resp['p1']['items'])
            item1id = items[0][0]
            item2id = items[1][0]
            opts = []
            opts.append(f'p1s=')
            opts.append(f'eq1={item1id}')
            opts.append(f'eq2={item2id}')
            opts.append(f'p1a={chosen_abil}')
            opts.append(f'chat=')
            opts.append('action=attack')
            opts.append(f'ts={ts}')
            opts.append(f'battleid={battle_id}')
            opts.append(f'step={step}')
            opts.append(f'intro=0')
            opts.append('status=1')
            print(
                f'Battledome: Attacking with {items[0][1]} and {items[1][1]}')
            np.set_referer_path(path_arena)
            np.post(path_arena_ajax, *opts)
            resp = json.loads(np.content)
            if resp['battle']['prizes'] or 'prize_messages' in resp['battle']:
                prizes = ', '.join(
                    x['name'] for x in resp['battle']['prizes']) or "nothing"
                print(f'Battledome: Won {prizes}')
                if 'prize_messages' in resp['battle']:
                    prize_messages = resp['battle']['prize_messages']
                    if any('reached the item limit' in m
                           for m in prize_messages):
                        prizes_left = False
                    if any('reached the NP limit' in m
                           for m in prize_messages):
                        neopoints_left = False
                    print(f'Battledome: {prize_messages}')
                break
            # TODO: Detect defeat.
            elif step > 5:
                print(
                    f'Battledome: Took more than 5 steps. Something went wrong.'
                )