Jump to content

Getting the closest NPC for name and action (OSBot 2)


Botre

Recommended Posts

 

excuse syntax errors, I don't have the client downloaded.

private NPC getClosestNPC(String name, String action) { // not as pretty but less heavy method
        NPC closest = null;
        double lowest = Double.MAX_VALUE;
        
        for(NPC npc : getNpcs().getAll()) {
            final List<String> actions = Arrays.asList(npc.getDefinition().getActions());
            final double distance = npc.getPosition().distance(myPosition());
            if(actions.contains(action) && distance < lowest) {
                closest = npc;
                lowest = distance;
            }
        }
        return closest;
    }
    
    
    private NPC closestNPC(final String name, final String action) { // much prettier but more resourceful.
        final Filter<NPC> filter = new Filter<NPC>() {
            @Override
            public boolean accept(NPC npc) {
                return Arrays.asList(npc.getDefinition().getActions()).contains(action);
            }
        };
        
        final List<NPC> filtered = new ArrayList<>();
        for(NPC npc : getNpcs().getAll()) {
            if(filter.accept(npc))
                filtered.add(npc);
        }
        
        final Comparator<NPC> comparator = new Comparator<NPC>() {
            @Override
            public int compare(NPC o1, NPC o2) {
                return o1.getPosition().distance(myPosition()) - o2.getPosition().distance(myPosition());
            }
        };
        Collections.sort(filtered, comparator);
        
        return filtered.size() > 0 ? filtered.get(0) : null;
    }

 

I still don't get the difference between my version and your first method /:

Why should I use that one instead of mine?

The second one is really interesting, I'm not very familiar with custom filters, I guess I'll be looking into those soon ^^

 

Thanks smile.png

Edited by Botrepreneur
  • Like 1
Link to comment
Share on other sites

I still don't get the difference between my version and your first method /:

Why should I use that one instead of mine?

The second one is really interesting, I'm not very familiar with custom filters, I guess I'll be looking into those soon ^^

 

Thanks smile.png

Cleaner, easier to understand, not making un-needed objects. etc.

The second method is cooler, but keep in mind it's more resource heavy.

  • Like 1
Link to comment
Share on other sites

Guest
This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...