Botre Posted June 20, 2015 Posted June 20, 2015 /** * Created by Bjorn on 20/06/2015. */ public abstract class InventoryMonitor extends Thread { private final BotreScript script; /** * Previous and current copies of the inventory instance. */ private final Map<String, Integer> previous, current; public InventoryMonitor(final BotreScript script) { this.script = script; previous = new TreeMap<>(); current = new TreeMap<>(); } @Override public void run() { // Run thread while script is running. while (script.isRunning()) { Inventory inventory; if (script.isOnline() && (inventory = script.getInventory()) != null) { // Clear previous cache. previous.clear(); // Copy mappings of the current cache to the previous cache. previous.putAll(current); // Clear current cache. current.clear(); // Rebuild current cache. for (Item item : inventory.getItems()) { if (item != null ) { String name = item.getName(); if (name != null && !current.containsKey(name)) current.put(name, (int) inventory.getAmount(name)); } } } try { // Call onLoop and sleep for its return value. Thread.sleep(onLoop()); } catch (InterruptedException e) { e.printStackTrace(); } } } public abstract int onLoop(); public int getDifference(String name) { if (current.containsKey(name)) return current.get(name) - (previous.containsKey(name) ? previous.get(name) : 0); else if (previous.containsKey(name)) return 0 - previous.get(name); else return 0; } } 3
Woody Posted June 20, 2015 Posted June 20, 2015 You could include an example on how to use this method to simplify for some scripters. Other than that, good job!
Botre Posted June 21, 2015 Author Posted June 21, 2015 @Woody, here's a little example (written without an IDE, "fletchedBows" is a global variable holding the total amount of fletched bows). in onStart(): new InventoryMonitor(this) { @override public int onLoop() { fletchedBows += getDifference("Oak longbow"); return 100; } }.start();
Bobrocket Posted June 22, 2015 Posted June 22, 2015 This is a neat way of tracking an inventory! Mind if I use it in one of my scripts?
Botre Posted June 23, 2015 Author Posted June 23, 2015 This is a neat way of tracking an inventory! Mind if I use it in one of my scripts? No problemerino!
Joseph Posted July 22, 2015 Posted July 22, 2015 (edited) for those that need a replacement @Override public void run() { // Run thread while script is running. if (script != null) { while (script.getBot().getScriptExecutor().isRunning()) { Inventory inventory; if ((inventory = script.getInventory()) != null) { // Clear previous cache. previous.clear(); Edited July 22, 2015 by josedpay 1