Jump to content

Some help if possible, trying to get script to sit idling without lag


TheGreatests

Recommended Posts

Having some issues with my script lagging out, its basically just going to sit there and idle until my mule starts a trade.

 

Issues are it lags out after first trade or so.

Here is the code, if you have a better structure let me know. I was thinking of using Nodes but am alittle lazy and cant seem to find a good stable skeleton for nodes that I could use with this.

import org.osbot.rs07.script.ScriptManifest;

import java.awt.*;
import java.lang.String;
import java.text.Normalizer;

import org.osbot.rs07.api.Bank;
import org.osbot.rs07.api.map.Area;
import org.osbot.rs07.script.Script;
import org.osbot.rs07.api.model.NPC;
import org.osbot.rs07.api.model.Player;
import org.osbot.rs07.api.model.RS2Object;
import org.osbot.rs07.api.ui.RS2Widget;
import org.osbot.rs07.api.ui.Skill;
import org.osbot.rs07.api.ui.Tab;

import javax.swing.*;

@SuppressWarnings("unused")
@ScriptManifest(author = "Elvis", info = "Muler V2.7", name = "Mule Trader V2.7", version = 2.7, logo = "Trades your miner to collect the profit!")
public class ClayMule extends Script{
	private final Area TRADING_AREA = new Area(3185, 3437, 3181, 3434);
	private int claycount;
	private int clay = 435;
	private State state = State.STARTIT;
	private long elapsed;
	private String log;
	private boolean isRunning = true;
	private int world;
	private boolean condition;

	private enum State {
		Wait, TradeAccepted, STARTIT,Trade
	}
	@[member=Override]
	public int onLoop() throws InterruptedException {

		switch(state) {
		
		
		case Wait:
			Wait4Player();
			break;
			
		case Trade:
			Trade();
			break;
			
		case TradeAccepted:
			TradeAccept();
			break;
			
		case STARTIT:
			STARTIT();
			break;
		}
		return random(120, 360);
	}
	@[member=Override]
	public void onStart() {
		isRunning = true;

		random(18, 32);
		world = worlds.getCurrentWorld();



		Thread runTimeThread = new Thread() {

			@[member=Override]
			public void run() {
				try {
					RunTime();
				}
				catch (Exception e) {
					log(e.getMessage());
				}
			}
		};

		runTimeThread.start();
	}

	private void Wait4Player() throws InterruptedException {
		Player player = players.closest("xxxxxxxxxx");
		if(player.isInteracting(myPlayer())){
			log= "We detected that our mule is trading us";
			condition = true;
			log=("Our mule has activated one of our conditions to trade");
			state =State.Trade;
			log=("Switching to trade method");
			return;
		}
		else if(!player.isInteracting(myPlayer())){
				random(500,1200);
			}
		state = State.TradeAccepted;
	}

	private void TradeAccept() throws InterruptedException {

		//if(isTrading()) {

			if(trade.isFirstInterfaceOpen()) {
				//log=("We are in the first trade interface");
				//if(!trade.offer(435, inventory.getItem(clay).getAmount())) return;
				log=("We are in the first trade interface");
				sleep(880, 1350);
				RandomizeMouse(); RandomSleep();

				trade.acceptTrade(); sleep(1200, 2300); RandomizeMouse();
				log=("Accepted first trade interface");
				while(isTrading() && !trade.didOtherAcceptTrade()){
					random(600,1200);
				}
			}

			if(trade.isSecondInterfaceOpen()) {
				RandomSleep();
				trade.acceptTrade(); sleep(150, 300); RandomizeMouse();
				log=("Accepted second trade interface");
				while(isTrading() && !trade.didOtherAcceptTrade()){
					random(600,1200);
				}
			Wait4Player();
			}
		//	STARTIT();
	//	}
	}

	private void Trade() throws InterruptedException {
		sleep(1600, 2500);
		if(isTrading()) {
			log=("We are trading");
			TradeAccept();
		}
		else {
			if(getWorlds().getCurrentWorld() != 383) {
				log=("Detected we are in not in the world of our mule, hopping to world");
				worlds.hop(383); sleep(8*1000, 14*1000);
				return;
			}


			if(!TRADING_AREA.contains(myPlayer())) {
				log=("Moving to trade area");
				MoveToZone(TRADING_AREA);
				sleep(880, 1350);
				return;
			}


			Player player = players.closest("xxxxxx"); 

			if(player != null && condition == true) {
				if(!player.isVisible()) 
					camera.toEntity(player);
				sleep(650, 2450);
				player.hover(); sleep(400, 850);
				if(player.interact("Trade with")) {
					log=("Trading with Mule");
					condition = false;
					log("Our condition is now false, until mule trades us again");
					sleep(1250, 1650); RandomizeMouse(); sleep(4500, 6500);
					return;
				}
			}
		}
	}
	private void STARTIT() throws InterruptedException {
		log=("Idling until our mule activates us...");
		state = State.Wait;
		return;
	}
	@[member=Override]
	public void onExit() {
		isRunning = false;
		log="We are finished";
	}

	@[member=Override]
	public void onPaint(Graphics2D g) {
		claycount = (int) inventory.getAmount(434);
		int x = getMouse().getPosition().x;
		int y = getMouse().getPosition().y;

		g.drawLine(0, y, 765, y);
		g.drawLine(x, 0, x, 503);

		DrawUpdate(g);
	}


	private void DrawUpdate(Graphics2D g) {

		g.setColor(new Color(0, 0, 0, 80));
		g.fillRect(4, 280, 512, 58);

		g.setColor(Color.white);
		g.setFont(new Font("Consolas", Font.PLAIN, 12));
		g.drawString("RunTime: " + GetRunTime(), 14, 300);

		g.drawString("Clay traded over " + claycount, 170, 300);
		g.drawString("Status: " + log, 219, 325);
	}

	private void RunTime() throws InterruptedException {

		long startTime = System.currentTimeMillis();

		while(isRunning) {
			elapsed = (System.currentTimeMillis() - startTime);
			sleep(1000);
		}
	}

	/*private void LaunchGUI() {

	}

	private void CloseGUI() {

	} 
	 */



	private void sleep(int min, int max) throws InterruptedException {
		sleep(random(min, max));
	}

	private String GetRunTime() {

		long hours = (elapsed / (1000 * 60 * 60)) % 24;
		long minutes = (elapsed / (1000 * 60)) % 60;
		long seconds = (elapsed / 1000) % 60;

		return String.format("%02d:%02d:%02d", hours, minutes, seconds);
	}




	private void MoveToZone(Area zone) throws InterruptedException {

		walking.webWalk(zone.getRandomPosition());
	}

	private boolean isTrading() {
		return trade.isCurrentlyTrading();
	}

	private boolean isInRadius(NPC npc) {
		Player me = myPlayer();

		int x = me.getX(),
				y = me.getY();

		return new Area(x + 1, y + 1, x - 1, y - 1).contains(npc);
	}

	private void RandomizeMouse() {
		switch(random(0, 5)) {
		case 0:
			mouse.moveRandomly();
			break;
		case 1:
			mouse.moveOutsideScreen();
			break;
		case 2:
			mouse.moveSlightly();
			break;
		}
	}

	private void RandomSleep() throws InterruptedException {

		switch(random(0, 5)) {
		case 0:
			sleep(650, 1250);
			break;

		case 1:  
			sleep(1450, 2050);
			break;

		case 2: 
			sleep(2250, 2850);
			break;

		case 3:
			sleep(3050, 3850);
			break;
		}
	}
}


Link to comment
Share on other sites

You seem to be calling "random(xxx, yyy)" when you intend to call "sleep(xxx, yyy)", this will cause a lot of lag especially in the while loops. Try using a ConditionalSleep instead of the while, or a for like:

for (int s = 0; s < 10 && someCondition; s++) sleep(100, 200); // Sleeps 1-2s or until someCondition is true

Though ConditionalSleeps will be a better solution. I tend to avoid while loops due to these issues they can cause.

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

@@Lemons

 

EDIT: Nevermind, I wasn't paying attention.

 

---

 

Without having looked at his code, if he's "lagging out", I suspect that the problem isn't that he's making a lot of calls to random or to sleep. There is probably a null pointer error somewhere, and if a gun were pointed to my head and I had to throw out a wild guess, it would be that he isn't doing a nullity check on a player object before interacting with it.

 

@@TheGreatests

 

 

 

 thinking of using Nodes but am alittle lazy and cant seem to find a good stable skeleton

 

You don't learn new skills by being lazy and waiting until you are spoon fed.

Edited by Solzhenitsyn
Link to comment
Share on other sites

@@Lemons

 

EDIT: Nevermind, I wasn't paying attention.

 

---

 

Without having looked at his code, if he's "lagging out", I suspect that the problem isn't that he's making a lot of calls to random or to sleep. There is probably a null pointer error somewhere, and if a gun were pointed to my head and I had to throw out a wild guess, it would be that he isn't doing a nullity check on a player object before interacting with it.

 

@@TheGreatests

 

 

You don't learn new skills by being lazy and waiting until you are spoon fed.

 

Ahhh!!! I forgot about that, I am gonna modify it tomorrow with a scripter. I wanna make this sucker clean, nodes are easy but I have completely forgotten and lost my set up before.

 

Link to comment
Share on other sites

  • 2 weeks later...

Ahhh!!! I forgot about that, I am gonna modify it tomorrow with a scripter. I wanna make this sucker clean, nodes are easy but I have completely forgotten and lost my set up before.

 

public abstract class Node {

    protected final MethodProvider methods;

    public Node(final MethodProvider methods) {
        this.methods = methods;
    }

    public abstract boolean validate() throws InterruptedException;

    public abstract void execute() throws InterruptedException;
}
public final class ConcreteNode extends Node {

    public ConcreteNode(final MethodProvider methods) {
        super(methods);
    }

    @ Override
    public final boolean validate() throws InterruptedException {
        return false;
    }

    @ Override
    public final void execute() throws InterruptedException {

    }
}
public final class NodeExecutor {

    private final Node[] nodes;

    public NodeExecutor(final Node... nodes) {
        this.nodes = nodes;
    }

    public final void execute() throws InterruptedException {
        for (final Node node : nodes) {
            if(node.validate()) node.execute();
        }
    }
}
@ScriptManifest(author = "", name = "", info = "", logo = "", version = 0.1)
public final class ExampleScript extends Script {

    private NodeExecutor nodeExecutor;

    @ Override
    public final void onStart() {
        ConcreteNode concreteNode = new ConcreteNode(this);
        ConcreteNode anotherConcreteNode = new ConcreteNode(this);
        nodeExecutor = new NodeExecutor(concreteNode, anotherConcreteNode);
    }

    @ Override
    public final int onLoop() throws InterruptedException {
        if(nodeExecutor != null) nodeExecutor.execute();
        return random(100, 150);
    }
}
Edited by Explv
Link to comment
Share on other sites

public abstract class Node {

    protected final MethodProvider methods;

    public Node(final MethodProvider methods) {
        this.methods = methods;
    }

    public abstract boolean validate() throws InterruptedException;

    public abstract void execute() throws InterruptedException;
}
public final class ConcreteNode extends Node {

    public ConcreteNode(final MethodProvider methods) {
        super(methods);
    }

    @ Override
    public final boolean validate() throws InterruptedException {
        return false;
    }

    @ Override
    public final void execute() throws InterruptedException {

    }
}
public final class NodeExecutor {

    private final Node[] nodes;

    public NodeExecutor(final Node... nodes) {
        this.nodes = nodes;
    }

    public final void execute() throws InterruptedException {
        for (final Node node : nodes) {
            if(node.validate()) node.execute();
        }
    }
}
@ScriptManifest(author = "", name = "", info = "", logo = "", version = 0.1)
public final class ExampleScript extends Script {

    private NodeExecutor nodeExecutor;

    @ Override
    public final void onStart() {
        ConcreteNode concreteNode = new ConcreteNode(this);
        ConcreteNode anotherConcreteNode = new ConcreteNode(this);
        nodeExecutor = new NodeExecutor(concreteNode, anotherConcreteNode);
    }

    @ Override
    public final int onLoop() throws InterruptedException {
        if(nodeExecutor != null) nodeExecutor.execute();
        return random(100, 150);
    }
}

 

So this is a better structure for nodes then I am assuming. Should I use this structure instead of the one I am using now, if so, is there any special features added to this one?

 

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...