Jump to content

Script review


MarWo22

Recommended Posts

Spoiler

package priceLookup;


import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;


import org.osbot.rs07.api.ui.RS2Widget;
import org.osbot.rs07.api.Bank;
import org.osbot.rs07.api.Bank.BankMode;
import org.osbot.rs07.api.model.NPC;
import org.osbot.rs07.script.Script;
import org.osbot.rs07.script.ScriptManifest;
import org.osbot.rs07.utility.ConditionalSleep;

@ScriptManifest(author = "MarWo", info = "Looks for best unf margins and makes those potions.", logo = "", name = "UnfBot2", version = 0)

public class Bot extends Script {
	

	
	
	int HighestMarginUnfId;
	int HighestMarginHerbId;
	int HighestMarginHerbPrice;
	int HighestMarginUnfPrice;
	String HighestMarginHerbName;
	int CurrentlyMaking;
	int CurrentlyMakingUnf;
	int PotionsMade = 0;
	long PotionsPerHour;
	
	long lastAnimation = 0;
	
	boolean BankStocked = true;
	boolean BankHasHerbs = true;
	boolean FirstRun = true;
	
	private final Font paintFont = new Font("Dialog", Font.PLAIN, 12);
	private final Color textColour = Color.WHITE;
	private long timeStarted;
	private long timeRan;
	private String SmallSeconds;
	private String SmallHours;
	private String SmallMinutes;
	
	
	public void onStart() {
		
		log("Welcome to the unfinished potion money maker" );
		timeStarted = System.currentTimeMillis();
		
	}
	
	
	
	
	
	public void onExit() {
		log("Thank you for using this script!");
	}
	
	
	
	
	
	public int onLoop() throws InterruptedException {
		

			if (myPlayer().isAnimating()) {

	            lastAnimation = System.currentTimeMillis();
			}
			
			
			if(inventory.contains(227) && inventory.contains(CurrentlyMaking)) {
				potMaker();
			} else if((!inventory.contains(227) || !inventory.contains(CurrentlyMaking)) && BankStocked == true && !grandExchange.isOpen()) {
				bankHandler();
			} else {
			try {
				GEhandler();
			} catch (IOException e) {
				log("ERROR");
				
			}
			}
			
		return 100;
		
	}
	
	
	public void onPaint(Graphics2D g) {
		
		timeRan = System.currentTimeMillis() - timeStarted;
		PotionsPerHour = (int)(PotionsMade / ((System.currentTimeMillis() - timeStarted) / 3600000.0D));
		
		
		
		g.setColor(textColour);
		g.setFont(paintFont);
		
		g.drawString("Time Ran: " + ft(timeRan), 20, 200);
		g.drawString("Potions made: " + PotionsMade, 20, 220);
		g.drawString("Potions per hour: " + PotionsPerHour, 20 , 240);
	
			
		
	}
	
private String ft(long duration) {
		
		String res = "";
		long hours = TimeUnit.MILLISECONDS.toHours(duration);
		long minutes = TimeUnit.MILLISECONDS.toMinutes(duration) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(duration));
		long seconds = TimeUnit.MILLISECONDS.toSeconds(duration) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(duration));
		
		if(seconds < 10) {
			SmallSeconds = "0";
		} else {
			SmallSeconds = "";
		}
		
		if(minutes < 10) {
			SmallMinutes = "0";
		} else {
			SmallMinutes = "";
		}
		
		if(hours < 10) {
			SmallHours = "0";
		} else {
			SmallHours = "";
		}
		
		
		
		res = (SmallHours + hours + ":" + SmallMinutes + minutes + ":" + SmallSeconds + seconds);
		return res;
	}
	
	
	public void potMaker() throws InterruptedException {
		if(getWidgets().isVisible(270, 14)) {
			getWidgets().interact(270, 14, "Make");
			getMouse().moveOutsideScreen();
			sleep(random(500,2000));
		}else {
			
			if (System.currentTimeMillis() > (lastAnimation + 1500)) {
						inventory.interact("Use", 227);
						sleep(random(100,300));
						inventory.interact("Use", CurrentlyMaking);
					sleep(random(100,300));
						
			}
			}	
		}
	
	public void bankHandler() throws InterruptedException {
		if(!getBank().isOpen()) {
			getBank().open();
		} else {
			
			if(bank.contains(259)) {
				CurrentlyMaking = 259;
				CurrentlyMakingUnf = 101;
				BankHasHerbs = true;
				FirstRun = false;
			} else if(getBank().contains(2998)) {
				CurrentlyMaking = 2998;
				CurrentlyMakingUnf = 3002;
				BankHasHerbs = true;
				FirstRun = false;
			} else if(getBank().contains(261)) {
				CurrentlyMaking = 261;
				CurrentlyMakingUnf = 103;
				BankHasHerbs = true;
				FirstRun = false;
			} else if(getBank().contains(263)) {
				CurrentlyMaking = 263;
				CurrentlyMakingUnf = 105;
				BankHasHerbs = true;
				FirstRun = false;
			} else if(getBank().contains(265)) {
				CurrentlyMaking = 265;
				CurrentlyMakingUnf = 107;
				BankHasHerbs = true;
				FirstRun = false;
			} else if(getBank().contains(2481)) {
				CurrentlyMaking =  2481;
				CurrentlyMakingUnf = 2483;
				BankHasHerbs = true;
				FirstRun = false;
			} else {
				BankHasHerbs = false;
			}
			
			if(getBank().contains(227) && BankHasHerbs == true ) {
				BankStocked = true;
				
			} else {
				BankStocked = false;
			}
			
			PotionsMade = (int) (PotionsMade + this.inventory.getAmount(CurrentlyMakingUnf));
			bank.depositAll();
			sleep(random(100,500));
			if(BankStocked == true) {
			bank.withdraw(227, 14);
			sleep(random(100,500));
			bank.withdraw(CurrentlyMaking, 14);
			sleep(random(100,500));
			getBank().close();
			}
			}
		}
	
	public void GEhandler() throws InterruptedException, IOException {
		
		final GrandExchange ge = new GrandExchange();
		
		int BuyingPriceIritHerb = ge.getBuyingPrice(259);
		int SellingPriceIritHerb = ge.getSellingPrice(259);
		int BuyingPriceIritUnf = ge.getBuyingPrice(101);
		int SellingPriceIritUnf = ge.getSellingPrice(101);
		int PriceIrit = Math.max(BuyingPriceIritHerb, SellingPriceIritHerb);
		int PriceIritUnf = Math.min(BuyingPriceIritUnf, SellingPriceIritUnf);
		int IritMargin = PriceIritUnf - PriceIrit;
		
		int BuyingPriceToadflaxHerb = ge.getBuyingPrice(2998);
		int SellingPriceToadflaxHerb = ge.getSellingPrice(2998);
		int BuyingPriceToadflaxUnf = ge.getBuyingPrice(3002);
		int SellingPriceToadflaxUnf = ge.getSellingPrice(3002);
		int PriceToadflax = Math.max(BuyingPriceToadflaxHerb, SellingPriceToadflaxHerb);
		int PriceToadflaxUnf = Math.min(BuyingPriceToadflaxUnf, SellingPriceToadflaxUnf);
		int ToadflaxMargin = PriceToadflaxUnf - PriceToadflax;
		
		int BuyingPriceAvantoeHerb = ge.getBuyingPrice(261);
		int SellingPriceAvantoeHerb = ge.getSellingPrice(261);
		int BuyingPriceAvantoeUnf = ge.getBuyingPrice(103);
		int SellingPriceAvantoeUnf = ge.getSellingPrice(103);
		int PriceAvantoe = Math.max(BuyingPriceAvantoeHerb, SellingPriceAvantoeHerb);
		int PriceAvantoeUnf = Math.min(BuyingPriceAvantoeUnf, SellingPriceAvantoeUnf);
		int AvantoeMargin = PriceAvantoeUnf - PriceAvantoe;
		
		int BuyingPriceKwuarmHerb = ge.getBuyingPrice(263);
		int SellingPriceKwuarmHerb = ge.getSellingPrice(263);
		int BuyingPriceKwuarmUnf = ge.getBuyingPrice(105);
		int SellingPriceKwuarmUnf = ge.getSellingPrice(105);
		int PriceKwuarm = Math.max(BuyingPriceKwuarmHerb, SellingPriceKwuarmHerb);
		int PriceKwuarmUnf = Math.min(BuyingPriceKwuarmUnf, SellingPriceKwuarmUnf);
		int KwuarmMargin = PriceKwuarmUnf - PriceKwuarm;
		
		int BuyingPriceCadantineHerb = ge.getBuyingPrice(265);
		int SellingPriceCadantineHerb = ge.getSellingPrice(265);
		int BuyingPriceCadantineUnf = ge.getBuyingPrice(107);
		int SellingPriceCadantineUnf = ge.getSellingPrice(107);
		int PriceCadantine = Math.max(BuyingPriceCadantineHerb, SellingPriceCadantineHerb);
		int PriceCadantineUnf = Math.min(BuyingPriceCadantineUnf, SellingPriceCadantineUnf);
		int CadantineMargin = PriceCadantineUnf - PriceCadantine;
		 
		int BuyingPriceLantadymeHerb = ge.getBuyingPrice(2481);
		int SellingPriceLantadymeHerb = ge.getSellingPrice(2481);
		int BuyingPriceLantadymeUnf = ge.getBuyingPrice(2483);
		int SellingPriceLantadymeUnf = ge.getSellingPrice(2483);
		int PriceLantadyme = Math.max(BuyingPriceLantadymeHerb, SellingPriceLantadymeHerb);
		int PriceLantadymeUnf = Math.min(BuyingPriceLantadymeUnf, SellingPriceLantadymeUnf);
		int LantadymeMargin = PriceLantadymeUnf - PriceLantadyme;
		
		int HighestMargin = Math.max(IritMargin, Math.max(ToadflaxMargin, Math.max(AvantoeMargin, Math.max(KwuarmMargin, Math.max(CadantineMargin, LantadymeMargin)))));
		
		if(IritMargin == HighestMargin) {
			HighestMarginHerbId = 259;
			HighestMarginUnfId = 101;
			HighestMarginHerbPrice = PriceIrit;
			HighestMarginUnfPrice = PriceIritUnf;
			HighestMarginHerbName = "Irit";
			} else if(ToadflaxMargin == HighestMargin) {
				HighestMarginHerbId = 2998;
				HighestMarginUnfId = 3002;
				HighestMarginHerbPrice = PriceToadflax;
				HighestMarginUnfPrice = PriceToadflaxUnf;
				HighestMarginHerbName = "Toadflax";
			} else if(AvantoeMargin == HighestMargin) {
				HighestMarginHerbId = 261;
				HighestMarginUnfId = 103;
				HighestMarginHerbPrice = PriceAvantoe;
				HighestMarginUnfPrice = PriceAvantoeUnf;
				HighestMarginHerbName = "Avantoe";
			} else if(KwuarmMargin == HighestMargin){
				HighestMarginHerbId = 263;
				HighestMarginUnfId = 104;
				HighestMarginHerbPrice = PriceKwuarm;
				HighestMarginUnfPrice = PriceKwuarmUnf;	
				HighestMarginHerbName = "Kwuarm";
			} else if(CadantineMargin == HighestMargin) {
				HighestMarginHerbId = 265;
				HighestMarginUnfId = 107;
				HighestMarginHerbPrice = PriceCadantine;
				HighestMarginUnfPrice = PriceCadantineUnf;
				HighestMarginHerbName = "Cadantine";
			} else {
				HighestMarginHerbId = 2481;
				HighestMarginUnfId = 2483;
				HighestMarginHerbPrice = PriceLantadyme;
				HighestMarginUnfPrice = PriceLantadymeUnf;
				HighestMarginHerbName = "Lantadyme";
			}
		
		log("The margin of Irit = " + IritMargin);
		log("The margin of Toadflax = " + ToadflaxMargin);
		log("The margin of Avantoe = " + AvantoeMargin);
		log("The margin of Kwuarm = " + KwuarmMargin);
		log("The margin of Cadantine = " + CadantineMargin);
		log("The margin of Lantadyme = " + LantadymeMargin);
		
		log("The highest margin is " + HighestMarginHerbName + "(" + HighestMarginHerbId + ") with " + HighestMargin);
		
		NPC clerk = getNpcs().closest("Grand Exchange Clerk");
		
		
		
		if(!grandExchange.isOpen()) {
		if(!bank.isOpen()) {
			bank.open();
		}
		}
		getBank().depositAll();
		
		if(!bank.getWithdrawMode().equals(Bank.BankMode.WITHDRAW_NOTE)) {
			bank.enableMode(BankMode.WITHDRAW_NOTE);
		}
		getBank().withdrawAll(995);
		
		sleep(random(100,300));
		if(getBank().contains(101)) {
			getBank().withdrawAll(101);
			sleep(random(100,500));
		} 
		if(getBank().contains(3002)) {
			getBank().withdrawAll(3002);
			sleep(random(100,500));
		} 
		if(getBank().contains(103)) {
			getBank().withdrawAll(103);
			sleep(random(100,500));
		} 
		if(getBank().contains(105)) {
			getBank().withdrawAll(105);
			sleep(random(100,500));
		} 
		if(getBank().contains(107)) {
			getBank().withdrawAll(107);
			sleep(random(100,500));
		} 
		if(getBank().contains(2483)) {
			getBank().withdrawAll(2483);
			sleep(random(100,500));
		}
		sleep(random(100,500));
		getBank().close();
		
		if(!grandExchange.isOpen()) {
			if(clerk!=null) {
				clerk.interact("Exchange");
				sleep(random(200,500));
			}
		} else {
			
			grandExchange.collect();
			sleep(random(250,1000));
			abortOffers();
			sleep(random(200,500));
			
			if(inventory.contains(102)) {
				grandExchange.sellItem(102, PriceIritUnf, 5000);
				sleep(random(250,1000));
			} 
			if(inventory.contains(3003)) {
				grandExchange.sellItem(3003, PriceToadflaxUnf, 5000);
				sleep(random(250,1000));
			} 
			if(inventory.contains(104)) {
				grandExchange.sellItem(104, PriceAvantoeUnf, 5000);
				sleep(random(250,1000));
			} 
			if(inventory.contains(106)) {
				grandExchange.sellItem(106, PriceKwuarmUnf, 5000);
				sleep(random(250,1000));
			} 
			if(inventory.contains(108)) {
				grandExchange.sellItem(108, PriceCadantineUnf, 5000);
				sleep(random(250,1000));
			} 
			if(inventory.contains(2484)) {
				grandExchange.sellItem(2484, PriceLantadymeUnf, 5000);
				sleep(random(250,1000));;
			}
			if(FirstRun == true) {
				grandExchange.buyItem(259, "Irit", PriceIrit + 200, 500);
				sleep(random(250,1000));
				grandExchange.buyItem(227, "Vial", 5, 500);
				sleep(random(250,1000));
				grandExchange.collect();
				FirstRun = false;
			}
			grandExchange.buyItem(HighestMarginHerbId, HighestMarginHerbName, HighestMarginHerbPrice + 25, 1000);
			sleep(random(250,1000));
			grandExchange.buyItem(227, "Vial", 5, 1000);
			sleep(random(250,1000));
			grandExchange.close();
			sleep(random(100,500));
			getBank().open();
			sleep(random(100,500));
			getBank().depositAll();
			BankStocked = true;
			
		}
	}
	
	 private boolean toAbortOffers() {
	        return !getWidgets().containingActions(465,"Abort offer").isEmpty();
	    }

	    private void abortOffers() throws InterruptedException {
	        if (toAbortOffers()) {
	            ArrayList<RS2Widget> toAbort = (ArrayList<RS2Widget>) getWidgets().containingActions(465,"Abort offer");
	            for (int i = 0; i < toAbort.size(); i++) {
	                toAbort.get(i).interact("Abort offer");
	                int finalI = i;
	                new ConditionalSleep(10000) {
	                    @Override
	                    public boolean condition() {
	                        return Arrays.asList(toAbort.get(finalI).getInteractOptions()).contains("Abort offer");
	                    }
	                }.sleep();
	            }
	            sleep(random(800,1200));
	            getGrandExchange().collect();
	        }
	    }
}

 

 

GrandExchange Snippet:

Spoiler

package priceLookup;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;

/**
 * GrandExchange Price Class
 * 
 * @author Reid
 *
 */
public class GrandExchange {

	private static final String BASE = "https://api.rsbuddy.com/grandExchange?a=guidePrice&i=";

	/**
	 * Default Constructor
	 * 
	 */
	public GrandExchange() {

	}
	
	/**
	 * Gets the overall price of an item.
	 * 
	 * @param itemID
	 * @return itemPrice
	 * @throws IOException
	 */
	public int getOverallPrice(final int itemID) throws IOException {
		return parse(itemID,"overall");
	}

	
	/**
	 * Gets the buying price of an item.
	 * 
	 * @param itemID
	 * @return itemPrice
	 * @throws IOException
	 */
	public int getBuyingPrice(final int itemID) throws IOException {
		return parse(itemID,"buying");
	}
	
	/**
	 * Gets the selling price of an item.
	 * 
	 * @param itemID
	 * @return itemPrice
	 * @throws IOException
	 */
	public int getSellingPrice(final int itemID) throws IOException {
		return parse(itemID,"selling");
	}


	/**
	 * Retrieves the price of an item.
	 * 
	 * @param itemID
	 * @return itemPrice
	 * @throws IOException
	 */
	private int parse(final int itemID, String choice) throws IOException {
		final URL url = new URL(BASE + itemID);
		BufferedReader file = new BufferedReader(new InputStreamReader(url.openStream()));
		String line;
		String price = null;
		while ((line = file.readLine()) != null) {
			if (line.contains("{")) {
				price = (line).trim();
			}
		}
		if (choice.equals("buying")){
			price = price.substring(price.indexOf(",") + 10, nthOccurrence(price, ',', 1)).trim();
		} else if(choice.equals("selling")) {
			price = price.substring(nthOccurrence(price, ',', 2)  + 11 , price.indexOf("sellingQuantity") - 2).trim();
		} else {
			price = price.substring(price.indexOf(":") + 1, price.indexOf(",")).trim();
		}
		file.close();
		return Integer.parseInt(price);
	}

	private int nthOccurrence(String str, char c, int n) {
		int pos = str.indexOf(c, 0);
		while (n-- > 0 && pos != -1)
			pos = str.indexOf(c, pos + 1);
		return pos;
	}

	}

 

First of all im new to scripting and java. This is one of the first scripts i have ever made. Can you guys please tell me some things to improve in this script and on next scripts in the future. Because my script is really long while it doesnt do that much.  Thank you :)

Edited by MarWo22
Link to comment
Share on other sites

Just running over the code, there are lots of things that could be improved, but for the most part it is a good effort!

Instead of critiquing each and every thing, i'll give some general pointers for things to consider in future scripts that you write:

  • Think about conditions

OSRS is a live game, and as a result you cannot rely on the bot to successfully execute every interaction command. You have to take this into account when writing your script by making it conditional.

If you have multiple chained interactions, for example (arbitrarily), if you wanted to use a raw fish on a fire:

getInventory().interact("Raw salmon", "Use");
getObjects().closest("Fire").interact("Use");

Consider what happens if the script misclicks the raw salmon. Then, the script would move on to the next line of code, and attempt to interact 'use' on the fire. However, since an item is not selected, the fire doesn't have a use option, and thus the script is stuck (potentially permanently) hovering over the fire.

A better way to structure this would be as follows:

if (getInventory().isItemSelected()) { // Optionally add a check for which item is selected here also
  RS2Object fire = getObjects().closest("Fire");
  if (fire != null) fire.interact("Use");
} else {
  getInventory().interact("Raw salmon", "Use");
}

With regards to your code, this especially applies with banking!

  • Use names, not ids

Game ids are subject to change following game updates, albeit less so with item ids. Instead, filter things with names. Names are much less likely to change, and using them can make your code significantly more readable! As a general rule of thumb, if you're using an id at any point in your code, there's probably a neater way to solve the problem.

  • Conditional sleeps!

Sleeping for a static amount of time, i.e

sleep(random(200,500));
// OR
sleep(4000);
// ... etc

is very bad practice. Latency fluctuations, resource allocation and other factors can cause these seemingly stable sleep duration to fall out of sync with what you want to achieve. Instead, use conditional sleeps which will sleep until a threshold is met, or a condition evaluates to true. For example:

RS2Object tree = getObjects().closest("Tree");
if (tree != null && tree.interact("Chop down")) {
  boolean didIStartCutting = new ConditionalSleep(3000) {
    @Override public boolean condition() { return myPlayer().isAnimating(); }
  }).sleep();
}

This will sleep for 3000ms, or until your player is animating.

  • Avoid flags where possible

Flagging is a means of tracking your script status by updating the value of a global variable at a certain stage. While it may work well, it is generally considered poor practice to over use this technique as there are typically better ways structure code to avoid this situation. While you are a beginner, this is not the most serious of problems, but as you learn more about object orientation and programming concepts, you should try and use your knowledge of code structure to avoid this situation. This will make larger projects more digestible and will make debugging a lot easier!

________________________________________________________________________

Hopefully that was useful, let me know if you have any further questions. Good luck!

Best

Apa

  • Like 3
Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Recently Browsing   0 members

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