Jump to content

Creating Static Methods


Otterblast

Recommended Posts

Hello,

I am trying to condense my code by making my own API consisting of some small but helpful methods. Some of the problems I am having is when converting the methods from non-static into static so that I can be able to call them. I have been able to fix this for stuff like camera and mouse movements by initializing a new camera/mouse. Now I am working on a method that will sleep while under combat (don't need to add eating in yet).

The problem comes when I try to import it into a different script and use it there. When I try to call upon the method it says it needs to be a static method. I make the change to public static void, but then I get an error because myPlayer() is not a static method. So I either need to initialize the class before I call on the method or somehow make it so I can get the same result without using myPlayer() or initialize a Player that I can use. I am not really sure how to solve this problem and my guesses may be way off, which is why I have come here seeking help.

Here is the code for my method

public static void actionSleep() throws InterruptedException{
		sleep(random(1000,2000));
		
		while(myPlayer().isAnimating() || myPlayer().isMoving() || myPlayer().isUnderAttack() || myPlayer().getAnimation() == 426){
			
			int X = random(1,7);
			
			if(X == 4) {
				antiBans.shortTermAntiban();
			}
			
			sleep(random(300,500));
			
		}
		
	}

I also have another version based on the entity that doesn't need changing to be static but the problem with it is that even if I use the same entity I was supposed to attack it sometimes gets mixed up and will then sleep forever. While you might say I could just put in a condition for if my player isn't under attack I then run into the same problem of myPlayer() method not being a static method. Also this was meant to work for ranging as well but if you are safe-spotting your health bar doesn't pop up and therefore you aren't considered "under attack" - which makes sense. 

	public static void attackSleep(Entity X) throws InterruptedException{
		
		while(X.isVisible()) {
			int y = random(1,7);
			
			if(y == 4) {
				antiBans.shortTermAntiban();
			}
			
			sleep(random(300,500));
		}
		
	}

I could also pretty easily solve this if I could get a timer and then have a method with a loop like the following

Timer time = new Timer(2000); //sets timer of length 2 seconds

while(time.isRunning()){ if(myPlayer().getAnimation == X){ time.reset} sleep(500) }

but again with the same problem of needing myPlayer() and I haven't been able to find or make a timer script to my liking (I'm not that good of a programmer tbh).

 

So if anyone could help explain how to be able to use myPlayer() within a static method or reference a method as a non-static method I would greatly appreciate it. Also if you know of a timer script that would work in the way I would like that would be very useful. 

But most importantly I would like to learn a way to be able to either make my methods non-static so that I can reference them in different scripts, or how to initialize the stuff so that I can use OSBot's methods in a non-static way.

Link to comment
Share on other sites

6 hours ago, Otterblast said:

Hello,

I am trying to condense my code by making my own API consisting of some small but helpful methods. Some of the problems I am having is when converting the methods from non-static into static so that I can be able to call them. I have been able to fix this for stuff like camera and mouse movements by initializing a new camera/mouse. Now I am working on a method that will sleep while under combat (don't need to add eating in yet).

The problem comes when I try to import it into a different script and use it there. When I try to call upon the method it says it needs to be a static method. I make the change to public static void, but then I get an error because myPlayer() is not a static method. So I either need to initialize the class before I call on the method or somehow make it so I can get the same result without using myPlayer() or initialize a Player that I can use. I am not really sure how to solve this problem and my guesses may be way off, which is why I have come here seeking help.

Here is the code for my method





public static void actionSleep() throws InterruptedException{
		sleep(random(1000,2000));
		
		while(myPlayer().isAnimating() || myPlayer().isMoving() || myPlayer().isUnderAttack() || myPlayer().getAnimation() == 426){
			
			int X = random(1,7);
			
			if(X == 4) {
				antiBans.shortTermAntiban();
			}
			
			sleep(random(300,500));
			
		}
		
	}

I also have another version based on the entity that doesn't need changing to be static but the problem with it is that even if I use the same entity I was supposed to attack it sometimes gets mixed up and will then sleep forever. While you might say I could just put in a condition for if my player isn't under attack I then run into the same problem of myPlayer() method not being a static method. Also this was meant to work for ranging as well but if you are safe-spotting your health bar doesn't pop up and therefore you aren't considered "under attack" - which makes sense. 





	public static void attackSleep(Entity X) throws InterruptedException{
		
		while(X.isVisible()) {
			int y = random(1,7);
			
			if(y == 4) {
				antiBans.shortTermAntiban();
			}
			
			sleep(random(300,500));
		}
		
	}

I could also pretty easily solve this if I could get a timer and then have a method with a loop like the following

Timer time = new Timer(2000); //sets timer of length 2 seconds

while(time.isRunning()){ if(myPlayer().getAnimation == X){ time.reset} sleep(500) }

but again with the same problem of needing myPlayer() and I haven't been able to find or make a timer script to my liking (I'm not that good of a programmer tbh).

 

So if anyone could help explain how to be able to use myPlayer() within a static method or reference a method as a non-static method I would greatly appreciate it. Also if you know of a timer script that would work in the way I would like that would be very useful. 

But most importantly I would like to learn a way to be able to either make my methods non-static so that I can reference them in different scripts, or how to initialize the stuff so that I can use OSBot's methods in a non-static way.

There are a lot of different ways you can go about this.

You could extend the class from the MethodProvider class as Medusa stated, you would also need to exchangeContext() in the onStart() method of your script if you go that route.

That would look something like this.

First create a class that extends from the MethodProvider.

Quote

public class ExtendedMethodProvider extends MethodProvider {
    public void doLogic() {
        log("Some logic to execute here.");
    }
}

Than create and store that object in your script.

Quote

public class ExampleScript extends Script {

    private ExtendedMethodProvider extendedMethodProvider;

    @Override
    public void onStart() throws InterruptedException {
        extendedMethodProvider = new ExtendedMethodProvider();
        extendedMethodProvider.exchangeContext(getBot());
    }
    
}

 

You could also, just take in variables you need in that method as a parameter like such.

public static void actionSleep(Player myPlayer, int maxSleepTime, int checkInterval) throws InterruptedException {
    Random random = new Random(System.nanoTime());
    new ConditionalSleep(maxSleepTime, checkInterval) {
        @Override
        public boolean condition() throws InterruptedException {
            int x = (int) (random.nextFloat() * 7f);
            if (x == 4)
                antiBans.shortTermAntiban();
            return myPlayer.getInteracting() == null;
        }
    }.sleep();
}

Also here is a simple StopWatch class.

Quote


public final class StopWatch {
    private boolean isRunning = false;

    private long startTime;
    private long stopTime;

    /**
     * Retrieves the elapsed time in NanoSeconds that this StopWatch has been or has ran for.
     *
     * @return ElapsedTime in NanoSeconds.
     */
    public long getElapsedNanoSeconds() {
        return (isRunning) ? System.nanoTime() - startTime : stopTime - startTime;
    }

    /**
     * Retrieves the elapsed time in Milliseconds that this StopWatch has been or has ran for.
     *
     * @return ElapsedTime in Milliseconds.
     */
    public float getElapsedMilliseconds() {
        return getElapsedNanoSeconds() / 1_000_000f;
    }

    /**
     * Retrieves the elapsed time in Seconds that this StopWatch has been or has ran for.
     *
     * @return ElapsedTime in Seconds.
     */
    public float getElapsedSeconds() {
        return getElapsedMilliseconds() / 1_000f;
    }

    /**
     * Starts the StopWatch.
     */
    public void start() {
        isRunning = true;
        startTime = System.nanoTime();
    }

    /**
     * Stops the StopWatch.
     */
    public void stop() {
        isRunning = false;
        stopTime = System.nanoTime();
    }
}

 

Edited by BravoTaco
  • Like 2
Link to comment
Share on other sites

13 hours ago, BravoTaco said:

There are a lot of different ways you can go about this.

You could extend the class from the MethodProvider class as Medusa stated, you would also need to exchangeContext() in the onStart() method of your script if you go that route.

That would look something like this.

First create a class that extends from the MethodProvider.

Than create and store that object in your script.

 

You could also, just take in variables you need in that method as a parameter like such.



public static void actionSleep(Player myPlayer, int maxSleepTime, int checkInterval) throws InterruptedException {
    Random random = new Random(System.nanoTime());
    new ConditionalSleep(maxSleepTime, checkInterval) {
        @Override
        public boolean condition() throws InterruptedException {
            int x = (int) (random.nextFloat() * 7f);
            if (x == 4)
                antiBans.shortTermAntiban();
            return myPlayer.getInteracting() == null;
        }
    }.sleep();
}

Also here is a simple StopWatch class.

 

Ok so I was able to make the class work but now its having an error in runtime. I try to run a little tester script

package scripts;

import org.osbot.rs07.api.model.NPC;
import org.osbot.rs07.api.model.Player;
import org.osbot.rs07.script.Script;
import org.osbot.rs07.script.ScriptManifest;
import api.General;


@ScriptManifest(author = "Otterblast", name = "tester", info = "tests scripts", version = 0.1, logo = "")


public class tester extends Script {
	
	public void onStart() throws InterruptedException{
		log("started");
		
	}
	
	
	public int onLoop() throws InterruptedException {
		int[] gobID = {3029,3031,3032,3033,3034,3035};
		Player player = myPlayer();
		log("loop");
		NPC goblin = npcs.closest(gobID);
		if(goblin != null && !player.isUnderAttack()) {
			
			goblin.interact("Attack");
			General.actionSleep(player);
			
		}
		
		return 50;
	}
	

}

But whenever it gets to the General.actionSleep(player) I get an error as follows

ERROR][Bot #1][12/09 05:06:35 PM]: Error in bot executor or from Error class (and not Exception)!
java.lang.NoClassDefFoundError: api/General
	at scripts.tester.onLoop(tester.java:28)
	at org.osbot.rs07.event.ScriptExecutor$InternalExecutor.run(al:291)
	at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.ClassNotFoundException: api.General
	at java.net.URLClassLoader.findClass(Unknown Source)
	at java.lang.ClassLoader.loadClass(Unknown Source)
	at java.lang.ClassLoader.loadClass(Unknown Source)
	... 3 more

I tried looking up some stuff and it looks like the problem I am having is that means that the class is present in the classpath at Compile time, but it doesn't exist in the classpath at Runtime. Is there a way to make this work?

Here is the code for the actionSleep()

public class General extends MethodProvider{
	public static void actionSleep(Player myPlayer) throws InterruptedException{
		sleep(random(1000,1500));
		StopWatch timer = new StopWatch();
		timer.start();
		while(timer.getElapsedSeconds() < 1.5) {
			if(myPlayer.isAnimating() || myPlayer.isMoving() || myPlayer.isUnderAttack() || myPlayer.getAnimation() == 426){
			
				timer.reset();
				
			}
			int X = random(1,7);
			
			if(X == 4) {
				antiBans.shortTermAntiban();
			}
		}
		
	}
}

Any help appreciated!

 

EDIT:

I was able to solve this by moving the api to a new project then including it in the build path of the project containing my script.

Edited by Otterblast
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...