Import from initial project into Gradle for library support mostly

This commit is contained in:
dtookey 2023-08-07 06:33:20 -04:00
commit 08a27661b9
21 changed files with 2196 additions and 0 deletions

35
.gitignore vendored Normal file
View File

@ -0,0 +1,35 @@
.gradle
build/
!gradle/wrapper/gradle-wrapper.jar
!**/src/main/**/build/
!**/src/test/**/build/
### IntelliJ IDEA ###
.idea/
### Eclipse ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
bin/
!**/src/main/**/bin/
!**/src/test/**/bin/
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
### VS Code ###
.vscode/
### Mac OS ###
.DS_Store
out/

8
.idea/.gitignore vendored Normal file
View File

@ -0,0 +1,8 @@
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml

15
.idea/gradle.xml Normal file
View File

@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="GradleSettings">
<option name="linkedExternalProjectsSettings">
<GradleProjectSettings>
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="modules">
<set>
<option value="$PROJECT_DIR$" />
</set>
</option>
</GradleProjectSettings>
</option>
</component>
</project>

View File

@ -0,0 +1,6 @@
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="ReplaceUntilWithRangeUntil" enabled="true" level="WEAK WARNING" enabled_by_default="true" />
</profile>
</component>

10
.idea/misc.xml Normal file
View File

@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ExternalStorageConfigurationManager" enabled="true" />
<component name="FrameworkDetectionExcludesConfiguration">
<file type="web" url="file://$PROJECT_DIR$" />
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_1_8" project-jdk-name="openjdk-19" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>

6
.idea/vcs.xml Normal file
View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="" vcs="Git" />
</component>
</project>

27
build.gradle.kts Normal file
View File

@ -0,0 +1,27 @@
plugins {
kotlin("jvm") version "1.9.0"
application
}
group = "xyz.geniuscartel"
version = "1.0-SNAPSHOT"
repositories {
mavenCentral()
}
dependencies {
testImplementation(kotlin("test"))
}
tasks.test {
useJUnitPlatform()
}
kotlin {
jvmToolchain(8)
}
application {
mainClass.set("EntryKt")
}

1
gradle.properties Normal file
View File

@ -0,0 +1 @@
kotlin.code.style=official

BIN
gradle/wrapper/gradle-wrapper.jar vendored Normal file

Binary file not shown.

View File

@ -0,0 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.2-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

234
gradlew vendored Normal file
View File

@ -0,0 +1,234 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
APP_NAME="Gradle"
APP_BASE_NAME=${0##*/}
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"

89
gradlew.bat vendored Normal file
View File

@ -0,0 +1,89 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

12
settings.gradle.kts Normal file
View File

@ -0,0 +1,12 @@
pluginManagement {
repositories {
mavenCentral()
gradlePluginPortal()
}
}
plugins {
id("org.gradle.toolchains.foojay-resolver-convention") version "0.5.0"
}
rootProject.name = "RuneFactory"

View File

@ -0,0 +1,376 @@
import java.awt.MouseInfo
import java.awt.Point
import java.awt.Robot
import java.awt.event.InputEvent
import java.util.concurrent.TimeUnit
import kotlin.random.Random
/**
* Interface for controllers that provide input capabilities.
*
* This defines methods for mouse and keyboard input like:
*
* - Moving the mouse
* - Mouse clicks
* - Key presses
* - Scrolling
*
* Classes that implement this interface can serve as input automation controllers.
*/
interface InputController {
/**
* Moves the mouse to the given [Point].
*
* @param point The destination [Point] to move the mouse to.
*/
fun moveMouse(point: Point)
/**
* Performs a mouse click at the current pointer location.
*
* @param button The mouse button to click.
* e.g. [InputEvent.BUTTON1_MASK]
*/
fun mouseClick(button: Int)
/**
* Presses and releases the given key.
*
* @param keyCode The key code of the key to press.
*/
fun keyPress(keyCode: Int)
/**
* Performs a mousewheel scroll in motion.
*
* This will move the scroll wheel forward by the number of ticks
* over the duration. It will sleep for short intervals between
* ticks using the provided sleep duration and variance.
*
* @param sleepDur The base sleep duration between scroll ticks.
* @param sleepDurVariance The variance in sleep duration.
*/
fun scrollIn(sleepDur: Long, sleepDurVariance: Long)
/**
* Performs a mousewheel scroll out motion.
*
* Same as [scrollIn] but moves the scroll wheel backward.
*/
fun scrollOut(sleepDur: Long, sleepDurVariance: Long)
}
interface TemporalController {
/**
* Sleeps for the specified duration.
*
* This uses [TimeUnit.MILLISECONDS] to sleep for the given duration in milliseconds.
*
* @param dur The sleep duration in milliseconds.
*/
fun sleep(dur: Long) {
TimeUnit.MILLISECONDS.sleep(dur)
}
/**
* Sleeps for the specified duration with some variance.
*
* This will sleep for the given duration plus a random variance between 0 inclusive and [variance] exclusive.
* The variance is divided in half to generate a random positive value that is added to the duration.
*
* If the duration is negative or the variance is less than 1, this method
* will return immediately without sleeping.
*
* @param duration The base sleep duration in ms
* @param variance The amount of variance to add in ms. Gets divided in half
* and rolled as two separate random numbers to create a normal distribution
*/
fun sleepWithVariance(duration: Long, variance: Long) {
if (duration < 0 || variance <= 1) {
return
}
val dSize = (variance) / 2
val r1 = Random.nextLong(dSize)
val r2 = Random.nextLong(dSize)
sleep(duration + r1 + r2)
}
}
/**
* Data class to hold wiggle parameters for mouse movement.
*
* This simple data class holds two integer properties for x and y wiggle amounts.
* These are used when generating simulated mouse movements to add some variance
* and randomness to the coordinates.
*
* For example, if a target destination point is (100, 200), the wiggle params
* might generate an actual movement point like (102, 198) to add some randomness.
*
* Usage:
*
* ```
* val controller = DesktopController()
* val wiggle = WiggleParams(xWiggle = 10, yWiggle = 15)
*
* val target = Point(100, 200)
* val actual = controller.getAlmostPoint(target, wiggle) // (104, 197)
* ```
*
* @param xWiggle The max amount of variance in x direction. Default 25.
* @param yWiggle The max amount of variance in y direction. Default 25.
*/
data class WiggleParams(
val xWiggle: Int = 25,
val yWiggle: Int = 25
)
/**
* Interface for controllers that interact with the desktop.
*
* This defines methods for getting desktop state like the mouse pointer
* location.
*
* Classes that implement this can serve as desktop automation controllers.
*/
interface DesktopController {
/**
* Gets the current pointer/mouse location on the desktop.
*
* @return The current [Point] location of the mouse pointer.
*/
fun getPointerLocation(): Point {
return MouseInfo.getPointerInfo().location
}
/**
* Gets a "wiggly" point near the given point.
*
* This takes in a target [Point] and [WiggleParams] and returns a new
* point that is randomly offset from the target point based on the
* wiggle parameters.
*
* This is useful for adding variance to mouse movements.
*
* @param point The target point to wiggle around
* @param params The wiggle parameters
* @return A new [Point] randomly offset from the target point.
*/
fun getAlmostPoint(point: Point, params: WiggleParams): Point {
val xDel = Random.nextInt(0, params.xWiggle)
val yDel = Random.nextInt(0, params.yWiggle)
val xDir = if (Random.nextDouble() > 0.5) {
1
} else {
-1
}
val yDir = if (Random.nextDouble() > 0.5) {
1
} else {
-1
}
return Point(point.x + (xDel * xDir), point.y + (yDel + yDir))
}
}
/**
* Interface for full-featured desktop automation controllers.
*
* Automaton combines capabilities from other interfaces to create a controller that can:
*
* - Get desktop and mouse state information like pointer location via [DesktopController]
*
* - Perform mouse and keyboard input like clicks, key presses, and scrolling via [InputController]
*
* - Handle timing and delays between actions using [TemporalController]
*
* By composing multiple capabilities, Automaton aims to provide a simple yet powerful interface for implementing
* desktop automation routines.
*
* Typical usage involves:
*
* 1. Obtaining an Automaton instance bound to the current OS/desktop
* 2. Calling methods like [moveMouse] and [mouseClick] to perform actions
* 3. Using [sleep] and [sleepWithVariance] to add delays
*
* This interface allows the underlying OS/desktop implementation details to be abstracted and swapped as needed.
*/
interface Automaton : DesktopController, InputController, TemporalController
/**
* Desktop automation controller using java.awt.Robot.
*
* This provides mouse, keyboard, and timing control capabilities by
* wrapping the java.awt.Robot class.
*
* Key features:
*
* - Get current mouse/pointer location
* - Move mouse and perform clicks
* - Keyboard presses and hotkeys
* - Scroll wheel motions
* - Sleep/delay methods with variance
*
* RobotController aims to provide a simple and easy to use API for
* automating desktop interactions and workflows.
*
* Usage example:
*
* ```
* val robot = RobotController()
*
* // Move mouse to 100, 200
* robot.mouseMove(Point(100, 200))
*
* // Left click at current position
* robot.click(InputEvent.BUTTON1_MASK)
*
* // Press A key
* robot.keyPress(KeyEvent.VK_A)
* ```
*
* @param robot The Robot instance to use. A default is created if not provided.
*/
open class RobotController(private val robot: Robot = Robot()) : Automaton {
/**
* Moves the mouse cursor to the given [Point] destination.
*
* Uses the Robot [mouseMove] method to move the mouse cursor to the x and y
* coordinates specified by the provided [Point].
*
* Adding some random variance to the target [Point] can simulate human-like
* imperfect mouse movements.
*
* Example usage:
*
* ```
* val robot = RobotController()
*
* // Target destination point
* val target = Point(100, 200)
*
* // Move mouse to target
* robot.mouseMove(target)
* ```
*
* @param destination The [Point] representing the target x and y coordinates.
*/
override fun moveMouse(point: Point) {
robot.mouseMove(point.x, point.y)
}
/**
* Performs a mouse click of the specified button.
*
* This uses the Robot to press and release the given mouse button.
*
* A random sleep is added in between pressing and releasing the button
* to add variance and avoid robotic timing.
*
* Example usage:
*
* ```
* val robot = RobotController()
*
* // Perform left click at current mouse position
* robot.click(InputEvent.BUTTON1_MASK)
* ```
*
* @param button The button to click. Must be a valid constant like [InputEvent.BUTTON1_MASK].
*
* Returns immediately If button is negative. Button must be a positive integer.
*/
override fun mouseClick(button: Int) {
//guardian logic
if (button < 0) {
return
}
robot.mousePress(button)
//we add in some random time variance here to appear less robotic
sleepWithVariance(8, 8)
robot.mouseRelease(button)
}
/**
* Presses and releases the given key.
*
* This uses the Robot to simulate pressing and releasing the key with the given key code.
*
* A random sleep is added after pressing the key before releasing it to add variance
* and avoid robotic timing.
*
* Example usage:
*
* ```
* val robot = RobotController()
*
* // Press the 'A' key
* robot.keyPress(KeyEvent.VK_A)
* ```
*
* @param keyCode The key code of the key to press, such as [KeyEvent.VK_A].
*
* Returns immediately if keyCode < 0. This can be useful for skipping actions by passing -1
*/
override fun keyPress(keyCode: Int) {
//guardian logic
if (keyCode < 0) {
return
}
robot.keyPress(keyCode)
//we add in some random time variance here to appear less robotic
sleepWithVariance(8, 8)
robot.keyRelease(keyCode)
}
/**
* Scrolls the mouse wheel down by one unit.
*
* Uses the Robot [mouseWheel] method to scroll down and then sleeps
* for a random duration between 10-20ms to pace the scrolling.
*
* Example usage:
*
* ```
* val robot = RobotController()
*
* // Scroll down 5 units
* repeat(5) {
* robot.scrollDown()
* }
* ```
*/
override fun scrollOut(sleepDur: Long, sleepDurVariance: Long) {
robot.mouseWheel(1)
sleepWithVariance(sleepDur, sleepDurVariance)
}
/**
* Scrolls the mouse wheel up by one unit.
*
* Uses the Robot [mouseWheel] method to scroll up and then sleeps for a
* random duration between 10-20ms to pace the scrolling.
*
* Example usage:
*
* ```
* val robot = RobotController()
*
* // Scroll up 10 units
* repeat(10) {
* robot.scrollUp()
* }
* ```
*/
override fun scrollIn(sleepDur: Long, sleepDurVariance: Long) {
robot.mouseWheel(-1)
sleepWithVariance(sleepDur, sleepDurVariance)
}
}

8
src/main/kotlin/Entry.kt Normal file
View File

@ -0,0 +1,8 @@
import java.awt.Point
fun main() {
println("Hello")
// Routines.fullRunIncense(0, 0, 0, 257)
Routines.processInventoryAtFurnace(566)
}

View File

@ -0,0 +1,116 @@
/**
* A collection of helper functions for common utility tasks.
*/
object HelperFunctions {
/**
* Computes the total number of steps needed to process the given total volume.
*
* This takes the total volume that needs to be processed and th
* and calculates the total steps required.
* Usage examples:
* ```
* val total = 550
* val perStep = 200
* val steps = calculateTotalSteps(total, perStep) // 3 steps
*
* val steps = calculateTotalSteps(1000, 100) // 10 steps
* ```
*
* @param totalVolume the total amount that needs to be processed
* @param volumePerStep the amount to process per step
* @return the number of steps required to process the total volume
*/
fun calculateTotalSteps(totalVolume: Int, volumePerStep: Int) =
totalVolume / volumePerStep + if (totalVolume % volumePerStep > 0) {
1
} else {
0
}
/**
* Prints a progress report to console showing current step, total steps, elapsed time, and estimated remaining time.
*
* This takes the current step number, total steps, and elapsed duration and prints a progress report.
* Typical usage is to call this within a loop, passing the loop index for current step and total loop count.
*
*
* Usage example:
* ```
* val totalSteps = 100
* val start = System.currentTimeMillis()
* for (i in 1..totalSteps) {
* // Do work
*
* report(i, totalSteps, System.currentTimeMillis() - start)
* }
* ```
*
* @param step The current step number
* @param of The total number of steps
* @param dur The elapsed duration so far in milliseconds
*/
fun report(step: Int, of: Int, dur: Long) {
val remaining = (dur / step) * (of - step)
print("\rStep $step of $of (${prettyTimeString(dur)} complete\t|\t~${prettyTimeString(remaining)} remaining) ")
}
/**
* Converts a duration in milliseconds to a human-readable string.
*
* This takes a duration in ms and converts it to a formatted string like "2h13m4s".
*
* Usage example:
*
* ```
* val duration = 72134 // ms
* val timeStr = prettyTimeString(duration)
* // "1m12s"
* ```
*
* @param durationMillis The duration to convert, in milliseconds
* @return A string representation of the duration, in the format XhYmZs
*/
fun prettyTimeString(durationMillis: Long): String {
if (durationMillis == 0L) {
return "No time data yet"
}
val millisPerSecond = 1000L
val millisPerMinute = 60L * millisPerSecond
val millisPerHour = 60L * millisPerMinute
return if (durationMillis > millisPerHour) {
return "${durationMillis / millisPerHour}h${(durationMillis % millisPerHour) / millisPerMinute}m${(durationMillis % millisPerMinute) / millisPerSecond}s"
} else if (durationMillis > millisPerMinute) {
return "${(durationMillis % millisPerHour) / millisPerMinute}m${(durationMillis % millisPerMinute) / millisPerSecond}s"
} else {
"${(durationMillis % millisPerMinute) / millisPerSecond}s"
}
}
/**
* Gets the current mouse pointer location and returns it as a val declaration string.
*
* This method uses the [getPointerLocationAfter] method to get the current
* mouse pointer location after a small delay.
*
* It then formats this location into a string declaring a val with the provided
* variable name, like:
*
* ```
* val location = getPointerLocationAsValDeclarationString("clickPoint")
* // val clickPoint = Point(123, 456)
* ```
*
* The delay before getting the pointer location helps ensure the mouse has
* settled after any prior movements.
*
* @param varName The name to use for the variable in the declaration string.
* @return A string declaring a val with the pointer location.
*/
fun getPointerLocationAsValDeclarationString(orchestrator: Orchestrator, varName: String): String {
val info = orchestrator.getPointerLocationAfterDelay(5)
return "val $varName = Point(${info.x}, ${info.y})"
}
}

View File

@ -0,0 +1,254 @@
import java.awt.Point
import java.awt.event.InputEvent
/**
* Interface for orchestrating automated interactions with the game.
*
* Implementations of this interface handle executing workflows and routines to automate
* gameplay through an [Automaton] instance.
*/
interface Orchestrator {
/**
* The [Automaton] instance used by this orchestrator to interact with the game.
*/
val automaton: Automaton
/**
* Scrolls out to the specified height by repeating scroll in/out operations.
*
* This handles scrolling out by the given height through a series of repeated
* scroll in and scroll out operations using the [doLoop] method.
*
* Example usage:
*
* ```
* orchestrator.scrollOutToHeight(12, 2)
* ```
*
* @param height The height in game coordinates to scroll out to.
* @param scrollWaitAndVariance The number of milliseconds to wait between scroll actions.
*/
fun scrollOutToHeight(height: Int, scrollWaitAndVariance: Long = 10L) {
automaton.sleep(1000)
doLoop(height * 2, 1) {
automaton.scrollIn(scrollWaitAndVariance, scrollWaitAndVariance)
}
doLoop(height, 1){
automaton.scrollOut(scrollWaitAndVariance, scrollWaitAndVariance)
}
}
/**
* Draws a star shape by moving the mouse between points.
*
* This method takes in a center point and calculates offset points around it.
* It then moves the mouse between each point in sequence to draw a star shape.
*
* The offset points are calculated by moving left/right and up/down from the
* center point by a fixed offset amount.
*
* Usage Example:
* ```
* orchestrator.drawStar()
* ```
*
* @param p The center point of the star.
*/
fun drawStar(p: Point = automaton.getPointerLocation()) {
val offset = 100
val top = Point(p.x, p.y - offset * 2)
val topright = Point(p.x + offset * 2, p.y + offset)
val bottomright = Point(p.x + offset * 2, p.y)
val topleft = Point(p.x - offset * 2, p.y + offset)
val bottomleft = Point(p.x - offset * 2, p.y)
val points = arrayListOf(top, bottomleft, topright, topleft, bottomright)
for (i in 0 until 10) {
for (point in points) {
automaton.moveMouse(point)
automaton.sleep(32)
}
}
}
/**
* Moves the mouse to a point, left clicks, and sleeps.
*
* This method moves the mouse to the provided point location, left clicks
* at that location, sleeps for the specified duration plus a random variance.
*
* Typical usage is to provide a point where something needs to be clicked,
* along with a sleep duration to wait after clicking.
*
*
* Example usage:
*
* ```
* val clickPoint = Point(100, 200)
* orchestrator.moveMouseLeftClickAndSleep(clickPoint, 500)
* ```
*
* The random variance in sleep time helps match real human actions.
*
* @param p The point location to move the mouse and left click.
* @param sleepDuration The base duration in ms to sleep after clicking.
* @param sleepDurationVariance The allowed variance in the sleep duration.
*/
fun moveMouseLeftClickAndSleep(p: Point, sleepDuration: Long, sleepDurationVariance: Long = 1) {
automaton.moveMouse(p)
automaton.sleepWithVariance(100, 50)
//left click
automaton.mouseClick(InputEvent.BUTTON1_DOWN_MASK)
automaton.sleepWithVariance(sleepDuration, sleepDurationVariance)
}
/**
* Performs a countdown loop announcing each step.
*
* This method counts down from a provided number of seconds to 0.
*
* It calls the provided [announceFn] function on each step, passing the current step number.
* A sleep of 1 second is added between each step.
*
*
* Typical usage is to print a countdown message within [announceFn].
*
* Usage example:
*
* ```
*
* orchestrator.countdown(5) {
* print("\rCountdown: $step ")
* }
* ```
*
* @param nSeconds The number of seconds to count down.
* @param announceFn A callback function called each step, passed step number.
*/
fun countDownInSeconds(nSeconds: Int, announceFn: (step: Int) -> Unit) {
for (i in nSeconds downTo 0) {
announceFn(i)
automaton.sleep(1000)
}
}
/**
* Gets the mouse pointer location after a delay.
*
* This method uses a countdown loop to wait for the specified number of
* seconds, printing a countdown as it goes.
*
* After the delay, it calls the automation library's getPointerLocation()
* method to retrieve the current mouse pointer coordinates.
*
* The delay helps ensure any prior mouse movements have settled before
* sampling the location.
*
* Usage example:
*
* ```
* val location = orchestrator.getMouseLocationAfterDelay(5)
* println(location) // Prints current mouse location after 5 second delay
* ```
* @param delayInSeconds The number of seconds to wait before sampling pointer location.
* @return The mouse pointer location after the delay as a Point.
*/
fun getPointerLocationAfterDelay(delayInSeconds: Int): Point {
countDownInSeconds(delayInSeconds) {
print("\rtaking pointer snapshot in $it...")
if (it == 0) {
println("\r ")
}
}
return automaton.getPointerLocation()
}
/**
* Prompts the user to position the mouse and returns that position.
*
* This method prints a prompt message, then waits for the user to position
* the mouse.
*
* It then returns the current mouse position as a Point after a slight delay.
*
* The delay allows the mouse to settle before sampling its position.
*
* Usage example:
*
* ```
* val prompt = "Move mouse to top left corner"
* val pos = orchestrator.promptForMousePosition(prompt)
* println(pos)
* ```
*
* @param prompt The message to display to prompt user to position mouse.
* @return The Point position of the mouse after user positions it.
*/
fun promptUserForPoint(prompt: String): Point {
println(prompt)
countDownInSeconds(5) {
print("\rtaking point snapshot in $it... ")
if (it == 0) {
println("\r ")
}
}
return automaton.getPointerLocation()
}
/**
* Performs a repetitive task multiple times.
*
* This handles iterating over the loop, tracking progress, and calling the provided task function each iteration.
*
* Typical usage is to pass a task function that performs some unit of work. doLoop() will call that task function
* repeatedly to automate a repetitive process.
*
* Usage example:
*
* ```
* val totalItems = 1000
* val itemsPerBatch = 10
* orchestrator.doLoop(totalItems, itemsPerBatch){
* // Craft one item
* }
* ```
*
* @param totalVolume The total number of units that need to be processed.
* @param volumePerStep The number of units to process per iteration.
* @param task The function to call each iteration, passing the Orchestrator as argument.
*/
fun doLoop(
totalVolume: Int,
volumePerStep: Int,
task: (Orchestrator) -> Unit
) {
require(totalVolume > 0) {
"You must make at least 1 thing in total"
}
require(volumePerStep > 0) {
"You must consume at least 1 thing per step"
}
val totalSteps = HelperFunctions.calculateTotalSteps(totalVolume, volumePerStep)
val start = System.currentTimeMillis()
for (i in 0 until totalSteps) {
HelperFunctions.report(i + 1, totalSteps, System.currentTimeMillis() - start)
task(this)
}
print("\r ")
val finish = System.currentTimeMillis()
println("Finished everything in ${HelperFunctions.prettyTimeString(finish - start)}")
}
}

358
src/main/kotlin/RSLogic.kt Normal file
View File

@ -0,0 +1,358 @@
import java.awt.Point
import java.awt.event.KeyEvent
/**
* Interface for a RuneScape orchestrator that can execute bot actions.
*
* This defines the capabilities that a RuneScape orchestrator needs to
* coordinate and perform bot actions like banking, traveling, and crafting.
*
* Implementations will contain the game-specific logic to interact with the
* RuneScape client and APIs to carry out the actions.
*
* Usage example:
* ```
* val orch = RSOrchestrator.getInstance()
* val params = StandingTaskParams(...)
* RSOrchestrator.doStandingTask(orch, params)
* ```
*/
interface RSOrchestrator : Orchestrator {
companion object {
/**
* Performs a standing crafting task loop at the bank.
*
* This handles a simple crafting loop where the player stands at the bank and crafts.
*
* It withdraws items from the bank, crafts a batch of items, deposits crafted items,
* and repeats.
*
* Usage example:
* ```
* val orch = RSOrchestrator.getInstance()
* val params = StandingTaskParams(...)
* RSOrchestrator.doStandingTask(orch, params)
* ```
*
* @param orchestrator The [RSOrchestrator] that will execute the actions.
* @param params The [StandingTaskParams] configuring the task details.
* @return Unit.
*/
fun doStandingTask(orchestrator: RSOrchestrator, params: StandingTaskParams) {
orchestrator.doLoop(params.totalVolume, params.volumePerStep) {
orchestrator.processAtBank(params)
}
}
/**
* Performs a crafting workflow loop that involves traveling between a bank and crafting station.
*
* This handles the overall workflow orchestration of:
* 1. Withdrawing items from the bank.
* 2. Traveling to the crafting station.
* 3. Crafting items.
* 4. Traveling back to the bank when inventory is empty.
*
* It will repeat this loop for the specified total volume of items to craft, doing the given volume per loop iteration.
*
* Usage example:
*
* ```
* val orch = RSOrchestrator.getInstance()
* val params = TravelTaskParams(...)
* RSOrchestrator.doTravelTask(orch, params)
* ```
*
* @param orchestrator The [RSOrchestrator] instance that will execute the actual actions.
* @param params The [TravelTaskParams] configuring the crafting loop details.
* @return Unit.
*/
fun doTravelTask(orchestrator: RSOrchestrator, params: TravelTaskParams) {
orchestrator.doLoop(params.totalVolume, params.volumePerStep) {
orchestrator.processAtStationNearBank(params)
}
}
/**
* Gets an instance of the [RSOrchestrator].
*
* This provides access to the orchestrator instance that can be used to
* coordinate bot actions.
*
* @return The [RSOrchestrator] instance.
*/
fun getInstance(): RSOrchestrator {
return RSAgent()
}
} //end of companion object
/**
* Handles the crafting process when standing at the bank.
*
* This method orchestrates the workflow when standing at the bank:
*
* - Opens the bank interface by left-clicking near the provided bank point location.
* - Withdraws the desired inventory preset using the provided hotkey.
* - Opens the crafting interface using the provided crafting dialogue hotkey.
* - Clicks the default "Make" hotkey to start crafting.
* - Waits for the specified crafting duration plus random variance.
*
* Usage example:
* ```
* val params = StandingTaskParams(...)
* orchestrator.processAtBank(params)
* ```
*
* @param taskParams The StandingTaskParams configuring the task details like bank location, hotkeys, durations etc.
*/
fun processAtBank(taskParams: StandingTaskParams)
/**
* Handles the crafting workflow when at a station near the bank.
*
* This orchestrates the steps to craft items at a station near the bank:
*
* - Travels from the bank to the station by left-clicking near the bank point.
* - Waits for the randomized travel duration.
*
* - Withdraws the preset inventory from the bank using the hotkey.
* - Waits for the randomized bank interaction duration.
*
* - Travels to the crafting station by left-clicking the station point.
* - Waits for the randomized travel duration.
*
* - Opens the crafting interface using the provided hotkey.
* - Clicks the "Make" button using the hotkey to craft items.
* - Waits for the randomized crafting duration.
*
* Usage example:
* ```
* val params = TravelTaskParams(...)
* orchestrator.processAtStationNearBank(params)
* ```
*
* @param taskParams The TravelTaskParams configuring the task details like locations, durations, hotkeys etc.
*/
fun processAtStationNearBank(taskParams: TravelTaskParams)
/**
* Gets the screen point location of the bank.
*
* This returns the x,y screen coordinates where the bank is located, which can be used to interact with the bank.
*
* Usage:
*
* ```
* val bankPoint = orchestrator.getBankLocation()
*
* // Left click the bank location to open the interface
* orchestrator.moveMouseLeftClickAndSleep(bankPoint, 100)
*
* // Withdraw preset inventory at bank
* orchestrator.automaton.keyPress(KeyEvent.VK_F1)
* ```
*
* @return The Point representing the x,y screen coordinates of the bank location.
*/
fun getBankPoint(): Point
}
/**
* Implementation of [RSOrchestrator] using a [RobotController].
*
* This class handles executing RuneScape automation tasks by controlling
* the game client via image recognition and input emulation.
*
* Usage examples:
* Travel between bank and crafting station:
* ```
* val agent = RSAgent.getInstance()
* val travelParams = TravelTaskParams(...)
* agent.doTravelTask(agent, travelParams)
* ```
* Craft while standing at bank:
* ```
* val standingParams = StandingTaskParams(...)
* orchestrator.doStandingTask(agent, standingParams)
* ```
*
*
* @param automaton The [Automaton] instance used to control the game. Defaults to [RobotController].
*/
private class RSAgent(override val automaton: Automaton = RobotController()) : RSOrchestrator {
companion object {
/**
* Extra padding in milliseconds added before actions to account for latency. 500ms is entirely arbitrary. It is
* simply a value that works well during high-load periods. Better to be conservative than lossy.
*
* This defines an extra duration in milliseconds that is added to sleeps
* and waits.
*
* It is to account for latency in the system before actions like mouse moves
* and clicks actually take effect.
*/
private const val LATENCY_PADDING_MS: Long = 500L
/**
* The duration in milliseconds of one "tick". The duration of 600ms matches the tick duration of game servers.
*
* This defines the concept of a "tick" as a unit of time used for pacing actions.
*
* It is used in methods like [sleepForNTicks] to calculate sleep durations
* based on multiplying a number of ticks by this value.
*
* For example, 5 ticks with this value would be 5 * 600 = 3000ms sleep duration.
*/
private const val TICK_DURATION_MS = 600L
}
/*==============================================================================================================
interface implementation
==============================================================================================================*/
/**
* Handles the crafting process when standing at the bank.
*
* This method takes care of the workflow when standing at the bank:
* - Opens the bank interface by left-clicking near the provided bank point location.
* - Withdraws the desired inventory preset using the provided hotkey.
* - Opens the crafting interface using the provided crafting dialogue hotkey.
* - Clicks the default "Accept" hotkey to start crafting.
* - Waits for the specified crafting duration plus random variance.
*
* Usage example:
*
* ```
* val params = StandingTaskParams(...)
* orchestrator.processAtBank(params)
* ```
*
* @param taskParams The [StandingTaskParams] configuring the task details like bank location, hotkeys, and durations.
*/
override fun processAtBank(
taskParams: StandingTaskParams
) {
//open the bank located by the chest parameter
moveMouseLeftClickAndSleep(automaton.getAlmostPoint(taskParams.bankPoint, WiggleParams()), 900, 400)
//withdraw the desired inventory preset
automaton.keyPress(taskParams.bankPresetHotkey)
//sleep for a server tick
sleepForNTicks(1)
//open the crafting dialog with the correct hotkey
automaton.keyPress(taskParams.craftingDialogHotkey)
//sleep for a server tick
sleepForNTicks(1)
//press the "accept" default hotkey
automaton.keyPress(KeyEvent.VK_SPACE)
//wait for the desired time to finish
automaton.sleepWithVariance(taskParams.craftingWaitDurationMillis, taskParams.craftingWaitDurationVarianceMillis)
}
/**
* Handles the crafting process when at a station near the bank.
*
* This method orchestrates the workflow when at the crafting station:
*
* - Travels from the bank to the station by left-clicking near the bank point.
* - Waits for the randomized travel duration.
*
* - Withdraws the desired inventory preset using the provided hotkey.
*
* - Travels to the crafting station by left-clicking the station point.
* - Waits for the randomized travel duration.
*
* - Opens the crafting interface using the provided hotkey.
*
* - Waits for the randomized crafting duration.
*
* Usage example:
* ```
* val params = TravelTaskParams(...)
* orchestrator.processAtStationNearBank(params)
* ```
*
* @param taskParams The [TravelTaskParams] configuring the task details.
*/
override fun processAtStationNearBank(
taskParams: TravelTaskParams
) {
//move to the bank and open the interface
moveMouseLeftClickAndSleep(
automaton.getAlmostPoint(taskParams.bankPoint, WiggleParams()),
taskParams.travelDurationMillis,
taskParams.travelDurationVarianceMillis
)
//withdraw desired loadout
automaton.keyPress(taskParams.bankPresetHotkey)
sleepForNTicks(1)
//move to station and open the crafting dialog
moveMouseLeftClickAndSleep(taskParams.travelPoint, taskParams.travelDurationMillis, taskParams.travelDurationVarianceMillis)
//start the crafting task
automaton.keyPress(KeyEvent.VK_SPACE)
//wait for it to complete
automaton.sleepWithVariance(taskParams.craftingWaitDurationMillis, taskParams.craftingWaitDurationVarianceMillis)
}
/*==============================================================================================================
cheater functions
==============================================================================================================*/
/**
* Prompts the user to position the mouse and returns that position.
*
* This method prints a prompt message, then waits for the user to position
* the mouse.
*
* It then returns the current mouse position as a Point after a slight delay.
*
* The delay allows the mouse to settle before sampling its position.
*
* Usage example:
* ```
* // Get bank location from user mouse position
* val bankPoint = orchestrator.getBankPoint()
* // Left click the bank to open the interface
* orchestrator.automaton.mouseMove(bankPoint)
* orchestrator.automaton.mouseClick(InputEvent.BUTTON1_DOWN_MASK)
* ```
*
* @return The Point position of the mouse after user positions it.
*/
override fun getBankPoint(): Point {
return promptUserForPoint("Hold your mouse over the bank...")
}
/**
* Sleeps for a specified number of game ticks.
*
* This method calculates the total sleep duration based on the number of ticks
* and the tick duration constant. It then sleeps for that amount plus a small
* latency padding.
*
* A random variance is also added to the sleep duration to add some less-robotic behavior.
*
* Usage example:
* ```
* val ticks = 10 // Sleep for 10 game ticks
* orchestrator.sleepTicks(ticks)
* ```
*
* @param n The number of game ticks to sleep for.
*/
fun sleepForNTicks(n: Long) {
val latencyPadding = LATENCY_PADDING_MS
val baseWaitTime = n * TICK_DURATION_MS
automaton.sleepWithVariance(latencyPadding + baseWaitTime, 150)
}
}

407
src/main/kotlin/Routines.kt Normal file
View File

@ -0,0 +1,407 @@
import java.awt.Point
import java.awt.event.KeyEvent
/**
* Routines object containing reusable workflows for common scripts.
*
* This object encapsulates reusable routines for common botting workflows.
* It provides an easy way to invoke these flows without having to reimplement
* the lower-level actions each time.
*
* The routines are structured as standalone methods that accept the necessary
* parameters. This allows them to be called independently and composed in
* different combinations.
*
* For example, the fullRunIncense routine orchestrates the entire incense
* stick crafting workflow by invoking the individual steps:
*
* - cleanHerbs
* - cutIncenseSticks
* - coatIncenseSticks
* - infuseIncenseSticks
*
* The individual steps can also be called independently as needed.
*
* This structure makes the routines reusable, customizable, and composable.
* Scripts can invoke the routines directly rather than reimplementing the
* underlying actions. Parameters allow customizing volumes, locations etc.
*/
object Routines {
/**
* The duration in milliseconds of one game tick.
*
* This defines the amount of time that passes during one server game tick.
*
* All timing and delays should be multiples of this tick duration to align with the
* server ticks and avoid timing issues.
*/
const val TICK_DURATION_MS = 600L
/**
* Performs the full incense stick crafting process from start to finish.
*
* @param volHerbs The number of grimy herbs to clean.
* @param volLogs The number of magic logs to cut into sticks.
* @param volAshes The number of sticks to coat in ashes.
* @param volCleanHerbs The number of clean herbs to infuse into sticks.
*
* This handles the entire incense stick crafting process:
* - Cleaning grimy herbs
* - Cutting magic logs into sticks
* - Coating sticks in ashes
* - Infusing clean herbs into sticks
*
* It loops through each step based on the provided volumes, performing the
* actions at the bank.
*
* Usage example:
*
* ```
* val herbs = 1000
* val logs = 2000
* val ashes = 1500
* val cleanHerbs = herbs + 150
*
* Routines.fullRunIncense(herbs, logs, ashes, cleanHerbs)
* ```
*
* Progress is printed after each step. Total elapsed time is printed at the end.
*/
fun fullRunIncense(volHerbs: Int, volLogs: Int, volAshes: Int, volCleanHerbs: Int) {
val start = System.currentTimeMillis()
//initialize the shared agent and chest point
val agent = RSOrchestrator.getInstance()
val bankPoint = agent.getBankPoint()
// Loop to clean grimy herbs:
// Withdraw herb preset, clean without dialog at bank
if (volHerbs > 0) {
cleanHerbs(volHerbs, agent, bankPoint)
}
println("\rHerbs cleaned")
// Loop to cut magic logs into sticks:
// Withdraw log preset, cut logs using hotkey at bank
if (volLogs > 0) {
cutIncenseSticks(volLogs, agent, bankPoint)
}
println("\rLogs cut into sticks")
// Loop to coat sticks in ashes:
// Withdraw ash preset, coat sticks using hotkey at bank
if (volAshes > 0) {
coatIncenseSticks(volAshes, agent, bankPoint)
}
println("\rSticks coated in ashes")
// Loop to infuse clean herbs into sticks:
// Withdraw herb preset, infuse sticks using hotkey at bank
if (volCleanHerbs > 0) {
infuseIncenseSticks(volCleanHerbs, agent, bankPoint)
}
println("\rClean herbs infused")
val finish = System.currentTimeMillis()
agent.drawStar()
println("Entire chain finished in ${HelperFunctions.prettyTimeString(finish - start)}")
}
/**
* Cleans a specified volume of grimy herbs into clean herbs.
*
* @param volume The number of grimy herbs to clean.
* @param agent Optional. The Agent instance to use for banking actions.
* @param bankPoint Optional. The Point location of the bank to use.
*
* This handles the workflow of:
* - Withdrawing grimy herb preset
* - Cleaning grimy herbs without dialog
* - Depositing clean herbs
*
* It performs the actions at the bank location using the provided agent.
*
* Usage examples:
* ```
* val volume = 1000
* val bankPoint = Point(100, 200)
* val agent = RSAgent.getInstance()
* Routines.cleanHerbs(volume, agent, bankPoint)
* ```
* Can also omit agent and bankPoint to use defaults:
* ```
* Routines.cleanHerbs(1000)
* ```
*/
fun cleanHerbs(volume: Int, agent: RSOrchestrator = RSOrchestrator.getInstance(), bankPoint: Point = agent.getBankPoint()) {
val params = StandingTaskParams(
volume,
CommonVolumesPerStep.FullInventory,
bankPoint,
KeyEvent.VK_F1,
KeyEvent.VK_1,
0,
0
)
RSOrchestrator.doStandingTask(agent, params)
}
/**
* Cuts a specified volume of magic logs into incense sticks.
*
* @param volume The number of magic logs to cut into sticks.
* @param agent Optional. The Agent instance to use for banking actions.
* @param bankPoint Optional. The Point location of the bank to use.
*
* This handles the workflow of:
* - Withdrawing magic log preset
* - Cutting magic logs into incense sticks without dialog
* - Depositing incense sticks
*
* Usage examples:
* ```
* val logs = 1000
* val bankPoint = Point(100, 200)
* val agent = RSAgent.getInstance()
*
* Routines.cutIncenseSticks(logs, agent, bankPoint)
* ```
* Can also omit agent and bankPoint to use defaults:
* ```
* Routines.cutIncenseSticks(1000)
* ```
*/
fun cutIncenseSticks(volume: Int, agent: RSOrchestrator = RSOrchestrator.getInstance(), bankPoint: Point = agent.getBankPoint()) {
val params = StandingTaskParams(
volume,
CommonVolumesPerStep.FullInventory,
bankPoint,
KeyEvent.VK_F2,
KeyEvent.VK_2,
26000,
TICK_DURATION_MS,
)
RSOrchestrator.doStandingTask(agent, params)
}
/**
* Coats a specified volume of incense sticks with ashes.
*
* @param volume The number of incense sticks to coat with ashes.
* @param agent Optional Agent instance to use for banking actions.
* @param bankPoint Optional Point location of the bank to use.
*
* This handles the workflow of:
* - Withdrawing incense stick preset
* - Coating incense sticks with ashes using hotkey
* - Depositing coated sticks
*
* Usage examples:
* ```
* val sticks = 1000
* val bankPoint = Point(100, 200)
* val agent = RSAgent.getInstance()
*
* Routines.coatIncenseSticks(sticks, agent, bankPoint)
* ```
* Can also omit agent and bankPoint to use defaults:
*
* ```
* Routines.coatIncenseSticks(1000)
* ```
*/
fun coatIncenseSticks(volume: Int, agent: RSOrchestrator = RSOrchestrator.getInstance(), bankPoint: Point = agent.getBankPoint()) {
val params = StandingTaskParams(
volume,
CommonVolumesPerStep.CoatingIncenseWithAsh,
bankPoint,
KeyEvent.VK_F3,
KeyEvent.VK_3,
17000,
TICK_DURATION_MS,
)
RSOrchestrator.doStandingTask(agent, params)
}
/**
* Infuses a specified volume of incense sticks with clean herbs.
*
* @param volume The number of incense sticks to infuse with herbs.
* @param agent Optional Agent instance to use for banking actions.
* @param bankPoint Optional Point location of the bank to use.
*
* This handles the workflow of:
* - Withdrawing incense stick preset
* - Infusing incense sticks with herbs using hotkey
* - Depositing infused incense sticks
*
* Usage examples:
* ```
* val sticks = 1000
* val bankPoint = Point(100, 200)
* val agent = RSAgent.getInstance()
*
* Routines.infuseIncenseSticks(sticks, agent, bankPoint)
* ```
* Can also omit agent and bankPoint to use defaults:
* ```
* Routines.infuseIncenseSticks(1000)
* ```
*/
fun infuseIncenseSticks(volume: Int, agent: RSOrchestrator = RSOrchestrator.getInstance(), bankPoint: Point = agent.getBankPoint()) {
val params = StandingTaskParams(
volume,
CommonVolumesPerStep.InfusingIncenseWithHerb,
bankPoint,
KeyEvent.VK_F4,
KeyEvent.VK_4,
48600,
TICK_DURATION_MS,
)
RSOrchestrator.doStandingTask(agent, params)
}
/**
* Crafts potions at a bank location using hotkeys.
*
* @param volume The total number of potions to craft.
* @param agent The RSOrchestrator instance to use. Defaults to default instance.
* @param bankPoint The location of the bank. Defaults to agent's configured bank point.
*
* This method handles the workflow of crafting potions using hotkeys while standing at a bank:
*
* - It constructs a StandingTaskParams instance defining:
* - The volume, volume per trip, bank point, crafting hotkey, and other details
* - It calls the orchestrator's doStandingTask() method to execute the task.
*
* Usage example:
* ```
* val volume = 1000
* val bankPoint = Point(100, 200)
* val agent = RSAgent.getInstance()
* Routines.craftPotionsAtBank(volume, agent, bankPoint)
* ```
*
* Progress is automatically printed during execution.
*
* @deprecated This method needs validation before use in production.
*/
@Deprecated("Needs validation before you use it for realsies")
fun craftPotionAtBank(volume: Int, agent: RSOrchestrator = RSOrchestrator.getInstance(), bankPoint: Point = agent.getBankPoint()) {
val params = StandingTaskParams(
volume,
CommonVolumesPerStep.FullInventory,
bankPoint,
KeyEvent.VK_F6,
KeyEvent.VK_MINUS,
19200,
TICK_DURATION_MS,
)
RSOrchestrator.doStandingTask(agent, params)
}
/**
* Grinds potions using a well location for water.
*
* @param volume The total number of potions to make.
* @param travelDurationInMillis The time in ms for the agent to travel between the bank and the well.
* @param agent The RSOrchestrator instance to use. Defaults to the default instance.
* @param bankPoint The Point location of the bank. Defaults to the agent's configured bank point.
*
* This method handles the workflow of grinding potions using a well as the water source.
*
* It prompts the user to position the mouse over the well location to get its coordinates.
*
* It then constructs a TravelTaskParams instance to define:
* - The volume, volume per trip, bank point, well point, and other task details.
*
* It calls the orchestrator's doTravelTask() method to execute the grinding task.
*
* Usage example:
* ```
* val volume = 1000
* val travelDuration = 5000 // 5 seconds
* val bankPoint = Point(100, 200)
* val wellPoint = Point(300, 400) // Prompted from user
* Routines.potionGrindWithWell(volume, travelDuration, bankPoint, wellPoint)
* ```
*
* Progress is automatically printed during execution.
*
* @deprecated This method needs validation before use in production.
*/
@Deprecated("Needs validation before you use it for realsies")
fun potionGrindWithWell(
volume: Int,
travelDurationInMillis: Long,
agent: RSOrchestrator = RSOrchestrator.getInstance(),
bankPoint: Point = agent.getBankPoint()
) {
val well = agent.promptUserForPoint("Put your mouse over the well...")
val params = TravelTaskParams(
volume,
CommonVolumesPerStep.FullInventory,
bankPoint,
well,
KeyEvent.VK_F6,
-1, //since the travel point is also the dialogue creator, we can omit the hotkey
19200,
TICK_DURATION_MS,
travelDurationInMillis,
TICK_DURATION_MS
)
RSOrchestrator.doTravelTask(agent, params)
}
/**
* Processes a volume of inventory at a furnace near the bank.
*
* @param volume The number of inventory slots to process at the furnace.
*
* The following 2 values are hard coded from my own personal setup
* furnaceFromChest The Point location of the furnace from the bank chest.
* chestFromFurnace The Point location of the bank chest from the furnace.
*
* Uses an Agent instance for banking and traveling.
*
* This handles the workflow of:
* - Withdrawing bars at bank chest
* - Walking to furnace and processing bars into items
* - Walking back to bank and depositing processed items
*
* The furnace and bank locations are passed in as specific Point locations.
* The agent handles the navigation and banking actions.
*
* Usage example:
*
* ```
* Routines.processAtFurnaceNearBank(1500)
* ```
*
* Before processing, the camera is reset to align points.
*/
fun processInventoryAtFurnace(volume: Int) {
//these two points are specific to my computer. we need to export these into a file or something
val furnaceFromChest = Point(776, 321)
val chestFromFurnance = Point(1713, 843)
val agent = RSOrchestrator.getInstance()
val params = TravelTaskParams(
volume,
28,
chestFromFurnance,
furnaceFromChest,
KeyEvent.VK_F6,
-1, //since the travel point is also the dialogue creator, we can omit the hotkey
51000,
TICK_DURATION_MS,
2000,
TICK_DURATION_MS
)
println("Resetting the camera. We need to define the reset to compass button...")
agent.scrollOutToHeight(8)
RSOrchestrator.doTravelTask(agent, params)
}
}

View File

@ -0,0 +1,157 @@
import java.awt.Point
/**
* Interface for common task parameters used across automation routines.
*
* This defines standard fields needed by most routines like total volume,
* volume per step, and the Agent instance.
*
* @property totalVolume The total number of items to process in the routine.
* @property volumePerStep The volume of items to process per step.
* @property agent The Agent instance that will run the routine.
*/
interface TaskParams {
val totalVolume: Int
val volumePerStep: Int
}
/**
* Interface for bank related parameters used in automation routines.
*
* Routines that involve banking items will need bank specific
* configuration like location and preset hotkeys.
*
* This interface encapsulates those common bank parameters. Classes
* that represent task params should implement this if banking is required.
*
* @property bankPoint The Point location of the bank to use.
* @property bankPresetHotkey The bank preset hotkey to withdraw/deposit items.
*/
interface BankParams {
val bankPoint: Point
val bankPresetHotkey: Int
}
/**
* Interface for crafting related parameters used in automation routines.
*
* Routines that involve a crafting action like fletching, cooking, etc will
* need crafting specific configuration like hotkeys and timing.
*
* This interface encapsulates those common crafting parameters. Classes
* that represent task params should implement this if they involve crafting.
*
* @property craftingDialogHotkey The hotkey used to open the crafting dialog.
* @property craftingWaitDurationMillis Base time in ms to wait after crafting.
* @property craftingWaitDurationVarianceMillis Random variance added to wait.
*/
interface CraftingParams {
val craftingDialogHotkey: Int
val craftingWaitDurationMillis: Long
val craftingWaitDurationVarianceMillis: Long
}
/**
* Interface for travel related parameters used in automation routines.
*
* Routines that involve traveling between a bank and activity area (e.g.
* crafting, cooking) will need travel related configuration.
*
* This interface encapsulates those common travel params. Classes that
* represent travel task params should implement this interface.
*
* @property travelPoint The Point destination to travel to.
* @property travelDurationMillis The expected travel time in milliseconds.
* @property travelDurationVarianceMillis Random variance to apply to the
* travel time. This helps simulate human-like travel.
*/
interface TravelParams {
val travelPoint: Point
val travelDurationMillis: Long
val travelDurationVarianceMillis: Long
}
/**
* Task parameters for routines performed while standing in one spot.
*
* This represents routines like fletching, cooking, etc. that are done
* without traveling between a bank and activity area.
*
* @param totalVolume Total number of items to process.
* @param volumePerStep The volume of items to process per iteration.
* @param agent The Agent instance.
* @param bankPoint Location of the bank.
* @param bankPresetHotkey Bank preset hotkey to use.
* @param craftingDialogHotkey Hotkey to open crafting dialog.
* @param craftingWaitDurationMillis Crafting action duration.
* @param craftingWaitDurationVarianceMillis Random variance for duration.
*/
data class StandingTaskParams(
override val totalVolume: Int,
override val volumePerStep: Int,
override val bankPoint: Point,
override val bankPresetHotkey: Int,
override val craftingDialogHotkey: Int,
override val craftingWaitDurationMillis: Long,
override val craftingWaitDurationVarianceMillis: Long
) : TaskParams, BankParams, CraftingParams
/**
* Task parameters for routines that involve traveling.
*
* This encapsulates all the configuration needed for routines where the
* player travels between a bank and activity area for crafting, cooking, etc.
*
* It brings together the common [TaskParams], bank [BankParams], crafting
* [CraftingParams], and travel [TravelParams] parameters into one data class.
*
* @param totalVolume Total number of items to process.
* @param volumePerStep The volume of items per crafting iteration.
* @param agent The Agent instance.
* @param bankPoint The bank location.
* @param travelPoint The travel destination.
* @param bankPresetHotkey Hotkey for bank preset.
* @param craftingDialogHotkey Hotkey to open crafting dialog.
* @param craftingWaitDurationMillis Base crafting action time.
* @param craftingWaitDurationVarianceMillis Crafting time variance.
* @param travelDurationMillis Expected travel time.
* @param travelDurationVarianceMillis Travel time variance.
*/
data class TravelTaskParams(
override val totalVolume: Int,
override val volumePerStep: Int,
override val bankPoint: Point,
override val travelPoint: Point,
override val bankPresetHotkey: Int,
override val craftingDialogHotkey: Int = -1, //all current travel tasks click the thing that starts the crafting dialogue
override val craftingWaitDurationMillis: Long,
override val craftingWaitDurationVarianceMillis: Long,
override val travelDurationMillis: Long,
override val travelDurationVarianceMillis: Long
) : TaskParams, BankParams, CraftingParams, TravelParams
/**
* CommonVolumesPerStep provides constants for common inventory volumes used during routines.
*/
object CommonVolumesPerStep {
/**
* Full inventory volume constant.
*/
const val FullInventory = 28
/**
* Two-reagent full inventory volume constant.
* For example, when combining two items that fill the inventory.
*/
const val TwoReagentFullInventory = 14
/**
* Volume for coating incense sticks with ashes.
*/
const val CoatingIncenseWithAsh = 26
/**
* Volume for infusing incense sticks with herbs.
*/
const val InfusingIncenseWithHerb = 27
}

View File

@ -0,0 +1,72 @@
package controllers
import org.junit.Test
import org.junit.Assert.*
import java.awt.Point
class InputControllerTest {
private val controller = TestInputController()
@Test
fun testMoveMouse() {
val point = Point(100, 200)
controller.moveMouse(point)
assertEquals(point, controller.lastMovedPoint)
}
@Test
fun testMouseClick() {
controller.mouseClick(InputEvent.BUTTON1_MASK)
assertTrue(controller.button1Clicked)
}
@Test
fun testKeyPress() {
val keyCode = KeyEvent.VK_A
controller.keyPress(keyCode)
assertEquals(keyCode, controller.lastPressedKey)
}
@Test
fun testScrollIn() {
controller.scrollIn(10, 5)
assertTrue(controller.didScrollIn)
}
@Test
fun testScrollOut() {
controller.scrollOut(10, 5)
assertTrue(controller.didScrollOut)
}
private class TestInputController : InputController {
var lastMovedPoint: Point? = null
var button1Clicked = false
var lastPressedKey: Int? = null
var didScrollIn = false
var didScrollOut = false
override fun moveMouse(point: Point) {
lastMovedPoint = point
}
override fun mouseClick(button: Int) {
if (button == InputEvent.BUTTON1_MASK) {
button1Clicked = true
}
}
override fun keyPress(keyCode: Int) {
lastPressedKey = keyCode
}
override fun scrollIn(sleepDur: Long, sleepDurVariance: Long) {
didScrollIn = true
}
override fun scrollOut(sleepDur: Long, sleepDurVariance: Long) {
didScrollOut = true
}
}
}