Osrs Plugin Runelite Development: PvP Helper – Part 1


๐Ÿ”ฅ Unleash the Power with osrs plugin! ๐Ÿ’ฅ Get Ready for the Ultimate PvP Revolution with the Mind-Blowing Runelite PvP osrs Plugin! ๐Ÿš€ Are you tired of the same old battles in your favorite game? Brace yourself for an electrifying experience as we introduce the game-changer you’ve been waiting for โ€“ the Runelite PvP Plugin! ๐ŸŽฎ Say goodbye to ordinary PvP encounters and dive into an adrenaline-fueled world where every click counts! ๐Ÿ’ฃ

Runelite Osrs Plugins Documentation API

If you haven’t already check out:

How to Build Runelite in IntelliJ IDEA

Creating your first Runelite osrs Plugin

The RuneLite API Documentation serves as a comprehensive guide for developers seeking to harness the power of the RuneLite API in their Java projects. This documentation provides insights into the classes, interfaces, annotations, enums, and packages that constitute the RuneLite API, offering a roadmap for creating osrs plugins, extensions, or applications within the RuneLite framework.

osrs plugin documentation with runelite

To navigate and understand the intricacies of the RuneLite API, developers are encouraged to refer to the official documentation available at https://static.runelite.net/api/runelite-api/overview-tree.html. This link directs you to an overview tree that visually represents the hierarchical structure of the API, making it easier to comprehend the relationships between different components.

Here’s a brief guide on how to make the most of the RuneLite API documentation:

Explore Package Hierarchies for osrs plugins:

  • Packages are used to organize and group related classes, interfaces, enums, etc. in Java.
  • In this case, the packages include various sub-packages like net.runelite.api, net.runelite.api.annotations, and others.
  • These packages likely contain different functionalities or aspects of the software
  • Begin by exploring the various package hierarchies outlined in the documentation. Packages organize related functionalities, helping you pinpoint specific features or aspects of the API relevant to your development goals.
  • A good resource for exploring package hierarchies excluding runelite’s framework is at w3schools Java Packages

Understand Class and Interface Hierarchies for osrs plugins:

  • Classes represent blueprints for objects in Java.
  • The listed classes are organized hierarchically, starting from the most general (java.lang.Object) to more specific classes.
  • Delve into the class and interface hierarchies to grasp the blueprint of different elements in the RuneLite API. This hierarchical structure aids in understanding inheritance, relationships, and dependencies between classes and interfaces.
  • Interfaces declare abstract methods that concrete classes must implement.
  • The listed interfaces are organized hierarchically, showcasing the relationships between them.
  • For more info on Classes and interfaces use w3schools Java Class and Objects and Interface Classes
public interface NPC extends Actor
{
	/**
	 * Gets the ID of the NPC.
	 *
	 * @return the ID of the NPC
	 * @see NpcID
	 */
	int getId();

	@Override
	String getName();

	@Override
	int getCombatLevel();

Leverage Annotations and Enums for osrs plugins:

  • Annotations provide metadata about the program elements they annotate (e.g., classes, methods).
  • The listed annotations are organized hierarchically.
  • Annotations and enums play a crucial role in providing metadata and defining constant sets. Understand their hierarchies to correctly utilize them in your projects, ensuring your implementations align with the intended functionalities.
  • Information about Enums and Annotations can be found at w3schools Java Enums and Annotations

Refer to Enum Definitions for osrs plugins:

  • Enums define a fixed set of constants.
  • The listed enums are organized hierarchically, representing different types, states, or categories.
  • Enums, such as those defining chat message types or equipment slots, provide valuable constants. Refer to these enums for a clear understanding of the predefined values that can be utilized in your RuneLite projects.
public enum GameState
{
	/**
	 * Unknown game state.
	 */
	UNKNOWN(-1),
	/**
	 * The client is starting.
	 */
	STARTING(0),
	/**
	 * The client is at the login screen.
	 */
	LOGIN_SCREEN(10),

Navigate the Interface Hierarchy:

  • Interfaces outline contracts that classes must adhere to. Explore the interface hierarchy to identify the methods you need to implement for specific functionalities.

Stay Updated on Annotations:

  • Annotations in the API may provide additional information or directives. Familiarize yourself with these annotations and utilize them appropriately in your code.

Optimize Exploration with the Overview Tree:

  • The overview tree, accessible through the provided link, visually represents the entire API structure. Use it as a reference to navigate efficiently and understand the relationships between different components.
  1. How to Use:
    • Understanding the hierarchy helps developers navigate the codebase efficiently.
    • If you’re working on a specific feature or functionality, you can explore the relevant packages, classes, and interfaces.
    • You may need to implement or extend certain classes/interfaces, or use enums and annotations as specified in the hierarchy.
  2. Examples:
    • For instance, if you are working with events, you might be interested in classes like net.runelite.api.events.*.
    • If you are dealing with overlays, you may find relevant classes in the net.runelite.api.overlay package.
    • Enums such as net.runelite.api.ChatMessageType might be used to identify different types of chat messages.

Remember that specific functionality and usage depend on the actual implementation within each class, interface, annotation, or enum. Refer to the actual source code and documentation for detailed information on how to use these elements in your Java project.

As you embark on your RuneLite development journey, this documentation will serve as an invaluable companion, guiding you through the intricacies of the API and empowering you to create powerful and feature-rich additions to the RuneLite platform.

Writing the code Pvp osrs plugin

Creating a PvP (Player versus Player) plugin using the RuneLite API involves implementing features that enhance the player’s experience in PvP scenarios. Here’s a step-by-step guide on how to approach coding a PvP plugin using the RuneLite API:

Github Source: https://github.com/slyautomation/osrs_pvp_tutorial

osrs plugin introduction to coding

1. Define Plugin Functionality:

  • Clearly define the functionalities your PvP plugin will offer. This might include features like tracking player kills, displaying opponent health, or providing additional information during PvP encounters.

2. Identify Relevant API Components for osrs plugins:

  • Review the RuneLite API documentation to identify the classes, interfaces, and enums that are relevant to PvP interactions. Look for classes related to players, health bars, combat, and any other features you plan to implement.

3. Implement Event Listeners:

  • Utilize event listeners provided by the RuneLite API to capture PvP-related events.

4. Display PvP Information:

  • Use the Overlay API to display relevant information on the game screen during PvP encounters. Create custom overlays to show opponent health bars, kill counts, or any other information you deem useful.

5. Handle PvP Logic for the osrs plugin:

  • Implement the core PvP logic based on your defined functionalities. This may involve tracking player kills, calculating damage dealt, or displaying notifications for significant PvP events.

To begin, we must create several Java classes with specific functionalities. Firstly, a configuration class is needed to allow users to interact with and toggle features on and off. Next, an overlay class is required to monitor and present a table of player counts along with other relevant information. An item definition interface class should be implemented to offer methods for retrieving and modifying various properties of an item.

Additionally, a utility class should be developed to implement these classes and methods, specifically focusing on generating player versus player (PvP) data in the game. Classes for text and table components are necessary to display information on-screen. A panel class is also essential to exhibit information in the panel section of RuneLite. Lastly, the main plugin serves as the central component responsible for initiating, shutting down, and registering events to track all game content.

Let’s break down the code!

PvpConfig

This code defines a configuration interface for a RuneLite plugin related to player versus player (PvP) activities in the game. The osrs plugin offer various tools and features that can be configured by the user.

osrs plugin config settings for the pvp tool
  1. Configuration Interface:
    • The interface PvpToolsConfig extends Config and is annotated with @ConfigGroup("pvptools").
    • It defines several configuration items using the @ConfigItem annotation.
    • The purpose of this interface is to provide a set of configuration options for the PvP Tools plugin.
  2. Configuration Items:
    • The configuration items are methods annotated with @ConfigItem.
    • Each method represents a specific setting for the PvP Tools plugin, allowing the user to customize the behavior of the plugin.
  3. Boolean Configuration Items:
    • There are several boolean configuration items (e.g., countPlayers, hideOthers, hideFriends), which control whether certain features of the plugin are enabled or disabled.
  4. Color Configuration Items:
    • There are two color configuration items (highlightColor and fillColor) annotated with @Alpha. These define the colors used for highlighting certain elements in the game.
  5. Risk Calculator Configuration Item:
    • There is a boolean configuration item (riskCalculatorEnabled) that controls whether a risk calculator panel should be enabled in the PvP Tools Panel.
  6. Default Values:
    • Each configuration item has a default value specified by the default keyword. These default values are used if the user doesn’t explicitly change the settings.
  7. Position Annotation:
    • The position attribute in @ConfigItem is used to specify the order in which these configuration options should be displayed in the user interface.

Overall, this code defines a set of configuration options for a PvP Tools osrs plugin, allowing users to customize various aspects of the osrs plugin’s behavior, such as hiding certain players or NPCs, changing highlight colors, and enabling a risk calculator panel.

Package and Imports:

   package net.runelite.client.plugins.pvptools;

   import net.runelite.client.config.Config;
   import net.runelite.client.config.ConfigGroup;
   import net.runelite.client.config.ConfigItem;
   import net.runelite.client.config.Keybind;

This part of the code specifies the package name and imports necessary classes for the configuration.

Config Interface:

   @ConfigGroup("pvptools")
   public interface PvpToolsConfig extends Config
   {

The PvpToolsConfig interface extends the RuneLite Config interface and is annotated with @ConfigGroup("pvptools"), indicating that this configuration is part of the “pvptools” group.

Configuration Items:

The code defines several configuration items using the @ConfigItem annotation. Each configuration item has a key name, display name, description, default value, and position. Here’s an overview of the defined configuration items:

  • countPlayers: Boolean to count attackable players in PvP zones.
  • countOverHeads: Boolean to count the number of protection prayers used by attackable targets.
  • hideOthers: hide other objects that are not npc or players
  • hideOthers2D: hide other objects that are not npc or players but the elements such as spell animations and pvp skull or prayer overlays.
  • hideFriends: hides players that have been added as friends
  • hideClanMembers: hides clan members
  • hideLocalPlayer: hides the user/own player
  • hideLocalPlayer: hides the user’s prayer or pvp skulled overlays
  • hideNpcs: hides NPCs
  • hideNpcs2D: hides NPCs elements such as the speech prints e.g cows moo
  • hideOtherPlayersPets
  • hideAttackers: Boolean to hide the players that attack the user.
  • hideProjectiles: Enumeration specifying the mode for hiding the attack option (e.g., friends only).
  • hideEnemies: Hides other players depending on if hideattackers is enabled it will also hide players that are attackable.
  • riskCalculatorEnabled: Boolean to enable a risk calculator panel in the PvP Tools panel.
  • highlightColor: changes the color which the attackers will be outlined with.
  • fillColor: changes the which the attackers will be filled with by default it is transparent (non filled).
@ConfigItem(
		keyName = "countPlayers", // keyname referenced in the classes
		name = "Count Players", // name show in the panel and osrs plugin settings
		description = "When in PvP zones, counts the attackable players in and not in player's CC", 
		position = 0 // the order which the element sits in the panel of the osrs plugin settings section
	)
	default boolean countPlayers() // the method tickbox yes/no 

PvpConfig Java Class Code

https://github.com/slyautomation/osrs_pvp_tutorial/blob/main/pvptools/PvpToolsConfig.java

The code provides a structured way for users to configure various aspects of the PvP Tools osrs plugin within the RuneLite client.

Player Count Overlay for osrs plugin

This code defines a RuneLite overlay named PlayerCountOverlay as part of a PvP Tools osrs plugin. The overlay displays a table of player counts categorized as “Friendly” and “Enemy” in specific game regions, such as the Wilderness, PvP worlds, or Clan Wars regions.

osrs plugin firendly and enemy count overaly for runelite pvp tool

Let’s break down the code:

  1. Import Statements:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.util.Arrays;
import javax.inject.Inject;
import javax.inject.Singleton;
import net.runelite.api.Client;
import net.runelite.api.Varbits;
import net.runelite.api.WorldType;
import net.runelite.client.ui.overlay.Overlay;
import net.runelite.client.ui.overlay.OverlayLayer;
import net.runelite.client.ui.overlay.OverlayPosition;
import net.runelite.client.ui.overlay.OverlayPriority;
import org.apache.commons.lang3.ArrayUtils;

import static net.runelite.client.plugins.pvptools.PvpUtil.isDeadmanWorld;

Import statements for various classes and packages used in the code most important for this class is the overlay class and the methods inside that will allow this runelite osrs plugin to function.

  1. Annotations:
   @Singleton

The @Singleton annotation indicates that only one instance of this class should exist.

  1. Class Definition:
   public class PlayerCountOverlay extends Overlay

The class PlayerCountOverlay extends the RuneLite Overlay class, which is used for creating graphical overlays on the game screen specifally the net.runelite.client.ui.overlay.Overlay class.

  1. Constants:
   private static final int[] CLAN_WARS_REGIONS = {9520, 13135, 13134, 13133, 13131, 13130, 13387, 13386};
   private final PvpToolsPlugin plugin;
	 private final PvpToolsConfig config;
	 private final Client client;

An array of region IDs associated with Clan Wars regions and private variables for the osrs plugin, config and client class.

  1. Constructor:
   @Inject
   public PlayerCountOverlay(final PvpToolsPlugin plugin, final PvpToolsConfig config, final Client client)
   	{
		this.plugin = plugin;
		this.config = config;
		this.client = client;
		setLayer(OverlayLayer.ABOVE_WIDGETS);
		setPriority(OverlayPriority.HIGHEST);
		setPosition(OverlayPosition.TOP_LEFT);
		setPreferredPosition(OverlayPosition.TOP_LEFT);
	}

The constructor is annotated with @Inject and takes instances of PvpToolsPlugin, PvpToolsConfig, and Client as parameters. It initializes the overlay with specific settings such as layer, priority, and position.

Render Method

  1. Method Signature:
   @Override
   public Dimension render(Graphics2D graphics)

This method overrides the render method from some superclass (probably an interface or an abstract class) and takes a Graphics2D object as a parameter. The return type is Dimension.

  1. Condition Check:
   if (config.countPlayers() &&
       (client.getVarbitValue(Varbits.IN_WILDERNESS) == 1 || 
        WorldType.isPvpWorld(client.getWorldType()) ||
        ArrayUtils.contains(CLAN_WARS_REGIONS, client.getMapRegions()[0]) ||
        isDeadmanWorld(client.getWorldType())))

Checks several conditions using logical AND (&&). The conditions include checking if the player count is enabled (config.countPlayers()), and if the player is in the Wilderness (Varbits.IN_WILDERNESS), on a PvP world, in specific regions, or in a Deadman world. If all conditions are true, the following block of code will be executed.

Table Component Initialization

   TableComponent tableComponent = new TableComponent();

Initializes a TableComponent object. This is likely a custom component for rendering tables in the graphical user interface.

Table Rows and Elements Initialization

   TableElement[] firstRowElements = {
       TableElement.builder().content("Friendly").color(Color.GREEN).build(),
       TableElement.builder().content(String.valueOf(plugin.getFriendlyPlayerCount())).build()};
   TableRow firstRow = TableRow.builder().elements(Arrays.asList(firstRowElements)).build();

Initializes the elements for the first row of the table. It includes a cell with content “Friendly” in green color and another cell with the count of friendly players obtained from the plugin.getFriendlyPlayerCount() method.

Similar initialization is done for the second row with elements representing “Enemy” in red color and the count of enemy players.

  1. Adding Rows to Table:
   tableComponent.addRows(firstRow, secondRow);

Adds the previously created rows to the tableComponent.

  1. Rendering and Returning Result:
   return tableComponent.render(graphics);

Calls the render method of the tableComponent and returns the result as a Dimension object. This assumes that the render method of TableComponent returns a Dimension representing the size of the rendered component.

  1. Default Return:
   return null;

If the conditions in the initial if statement are not met, the method returns null.

In summary, this code is part of a rendering system for a graphical user interface. It checks certain conditions related to the player’s environment and, if met, creates a table component showing the count of friendly and enemy players in a specific format. If the conditions are not met, it returns null.

This method is called when the overlay should be rendered. It checks if player counting is enabled in the configuration and if the player is in relevant regions (Wilderness, PvP world, Clan Wars, or Deadman world). If conditions are met, it creates and renders a TableComponent displaying player counts.

  • It creates a table with two rows: one for “Friendly” players and one for “Enemy” players.
  • The player counts are retrieved from the PvpToolsPlugin instance (plugin.getFriendlyPlayerCount() and plugin.getEnemyPlayerCount()).
  • The table is rendered using the TableComponent class.
  1. Table Rendering:
   TableComponent tableComponent = new TableComponent();
   TableElement[] firstRowElements = { ... };
   TableRow firstRow = TableRow.builder().elements(Arrays.asList(firstRowElements)).build();
   // Similar setup for the second row
   tableComponent.addRows(firstRow, secondRow);
   return tableComponent.render(graphics);

The code sets up the TableComponent with two rows, each containing elements for player counts, and then renders the table using the provided Graphics2D object.

  1. Condition Check:
   if (config.countPlayers() && (client.getVarbitValue(Varbits.IN_WILDERNESS) == 1 || WorldType.isPvpWorld(client.getWorldType())
       || ArrayUtils.contains(CLAN_WARS_REGIONS, client.getMapRegions()[0]) ||
       WorldType.isDeadmanWorld(client.getWorldType())))

This condition checks if player counting is enabled in the configuration and if the player is in a relevant game region (Wilderness, PvP world, Clan Wars, or Deadman world).

PlayerCountOverlay Java Class Code

https://github.com/slyautomation/osrs_pvp_tutorial/blob/main/pvptools/PlayerCountOverlay.java

In summary, the PlayerCountOverlay class is a RuneLite overlay that displays a table of player counts categorized as “Friendly” and “Enemy” in specific game regions. The overlay is conditionally rendered based on the player’s location and configuration settings.

Pvp Item Definition for osrs plugin

This code defines an interface named ItemDefinition that represents the definition of an in-game item in the context of the osrs plugin. This interface provides methods to retrieve and modify various properties of an item, such as its name, ID, noted status, price, membership requirement, stackability, tradeability, and more.

Let’s go through the methods defined in the interface:

  1. getName(): Returns the name of the item.
  2. setName(String name): Sets the name of the item.
  3. getId(): Returns the ID of the item.
  4. getNote(): Returns a value indicating whether the item is noted. Returns 799 if noted, -1 otherwise.
  5. getLinkedNoteId(): Returns the ID of the noted or unnoted variant of this item.
  6. getPlaceholderId(): Returns the ID of the normal or placeholder variant of this item.
  7. getPlaceholderTemplateId(): Returns a value indicating whether the item is a placeholder. Returns 14401 if a placeholder, -1 otherwise.
  8. getPrice(): Returns the store price of the item, which can be used to calculate high and low alchemy values.
  9. isMembers(): Checks whether the item is available only to members.
  10. isStackable(): Checks whether the item can stack in a player’s inventory.
  11. isTradeable(): Returns whether or not the item can be sold on the grand exchange.
  12. setTradeable(boolean yes): Sets the tradeability status of the item.
  13. getInventoryActions(): Returns an array of possible right-click menu actions the item has in a player’s inventory.
  14. getShiftClickActionIndex(): Returns the menu action index of the shift-click action.
  15. setShiftClickActionIndex(int shiftClickActionIndex): Sets the menu action index of the shift-click action.
  16. resetShiftClickActionIndex(): Resets the menu action index of the shift-click action to its default value.
  17. setModelOverride(int id): Allows making certain (ground) items look like different ones by providing the item ID of the item with the desired model.

ItemDefinition Java Class Code

https://github.com/slyautomation/osrs_pvp_tutorial/blob/main/pvptools/ItemDefinition.java

This interface serves extra functionality to the core ItemDefinition class already in runelite and is a blueprint for defining and manipulating the properties of in-game items within the context of a game osrs plugin, allowing for customization and interaction with various aspects of item behavior.

Pvp Utility for osrs plugin

This Java class, named PvpUtil, contains utility methods related to player versus player (PvP) activities in the game “Old School RuneScape” (OSRS). Let’s go through the key methods in this utility class:

  1. getItemDefinition(int id): This method is incomplete (return null;). It is intended to retrieve the item composition (definition) corresponding to an item’s ID. The actual implementation of this method, which should return a valid ItemDefinition object, is not provided in the code.
  2. isDeadmanWorld(final Collection<WorldType> worldTypes): This method checks if a given collection of WorldType contains the “Deadman” world type. It returns true if at least one Deadman world type is found in the collection, and false otherwise.
  3. getWildernessLevelFrom(WorldPoint point): Given a WorldPoint (a point in the game world), this method calculates and returns the wilderness level based on the Y-coordinate of the point. The wilderness is divided into upper and under levels, and the method determines whether the provided point is in the upper or under level.
  4. isAttackable(Client client, Player player): This method determines whether another player is attackable based on various conditions. It checks if the local player is in the Wilderness, a PvP world, or a Deadman world. The conditions for attackability are different based on these factors, considering combat levels and wilderness levels.
  5. calculateRisk(Client client, ItemManager itemManager): This method calculates the risk (wealth) of the local player based on the items they have equipped and in their inventory. It considers the prices of tradeable items and the defined prices for non-tradeable items (using the getItemDefinition method). The calculated wealth is returned as an integer.

Please note that the getItemDefinition is superceded/provided by the ItemDefinition class previously mentioned above. Additionally, this class assumes that relevant dependencies (Client, Player, ItemManager, etc.) are provided from the game environment during execution.

Pvp Untility Packages

package net.runelite.client.plugins.pvptools;

import java.util.*;

import net.runelite.api.Client;
import net.runelite.api.InventoryID;
import net.runelite.api.Item;
import net.runelite.api.Player;
import net.runelite.api.Varbits;
import net.runelite.api.WorldType;
import net.runelite.api.coords.WorldPoint;
import net.runelite.client.game.ItemManager;
import net.runelite.client.util.QuantityFormatter;
import org.apache.commons.lang3.ArrayUtils;

import javax.annotation.Nonnull;

import static net.runelite.api.WorldType.DEADMAN;

Most of the packages and methods for the utility class will be for objects or data in the game such as player/enemy stats and equipment and determining location within the game such as wilderness level or if the server world is pvp zone.

Pvp Get Item Definition

	@Nonnull
	static ItemDefinition getItemDefinition(int id)
	{
		return null;
	} // 

This will be used to determine whats equipped (the unique identifier) and how much the items are worth for both the player and enemy.

Searching on OSRSBox you can see what each item’s id (swordfish id = 373).

Pvp Is Deadman World

	private static final EnumSet<WorldType> DEADMAN_WORLD_TYPES = EnumSet.of(
			DEADMAN
	);
	
		public static boolean isDeadmanWorld(final Collection<WorldType> worldTypes)
	{
		return worldTypes.stream().anyMatch(DEADMAN_WORLD_TYPES::contains);
	}

This is getting a collection of available deadman worlds and when used will return true or false if the current world server logged in is a deadman world.

Pvp Get Wilderness Level From

	public static int getWildernessLevelFrom(WorldPoint point)
	{
		int y = point.getY();

		int underLevel = ((y - 9920) / 8) + 1;
		int upperLevel = ((y - 3520) / 8) + 1;

		return y > 6400 ? underLevel : upperLevel;
	}

This is getting the area for which the wilderness precides. note the 2 levels upper and under and y is the determining factor for identfying if the player is in the wilderness zone.

Pvp is Attackable

    public static boolean isAttackable(Client client, Player player)
	{
		int wildernessLevel = 0;

		if (!(client.getVar(Varbits.IN_WILDERNESS) == 1
				|| WorldType.isPvpWorld(client.getWorldType())
				|| isDeadmanWorld(client.getWorldType())))
		{
			return false;
		}

		if (isDeadmanWorld(client.getWorldType()))
		{
			return true;
		}

		if (WorldType.isPvpWorld(client.getWorldType()))
		{
			if (client.getVar(Varbits.IN_WILDERNESS) != 1)
			{
				return Math.abs(client.getLocalPlayer().getCombatLevel() - player.getCombatLevel()) <= 15;
			}
			wildernessLevel = 15;
		}
		return Math.abs(client.getLocalPlayer().getCombatLevel() - player.getCombatLevel())
				< (getWildernessLevelFrom(client.getLocalPlayer().getWorldLocation()) + wildernessLevel);
	}

isAttackable is takes all of the previous functions isDeadmanWorld and getWildernessLevelFrom and adds the player’s combat level.

Pvp Calculate Risk

public static int calculateRisk(Client client, ItemManager itemManager)
	{
		if (client.getItemContainer(InventoryID.EQUIPMENT) == null)
		{
			return 0;
		}
		if (client.getItemContainer(InventoryID.INVENTORY).getItems() == null)
		{
			return 0;
		}

Next is the calculateRisk function, which firstly check both the players equipment and inventory to see if its null return 0 GP worth.

Pvp Items Equipment & Inventory

		Item[] items = ArrayUtils.addAll(Objects.requireNonNull(client.getItemContainer(InventoryID.EQUIPMENT)).getItems(),
				Objects.requireNonNull(client.getItemContainer(InventoryID.INVENTORY)).getItems());

This is itering through every equipment item and inventory item and storing into an array items.

TreeMap<Integer, Item> priceMap = new TreeMap<>(Comparator.comparingInt(Integer::intValue));
		int wealth = 0;

Create a mapping list with the id of the item and the value

Certainly! Let’s break down the code step by step:

Initialization:

   int wealth = 0;

Initializes an integer variable wealth to zero. This variable will be used to accumulate the total wealth.

Loop Through Items

   for (Item i : items)
   {
       // ...
   }

Iterates through each Item in the items collection.

Calculate Item Value:

   int value = (itemManager.getItemPrice(i.getId()) * i.getQuantity());

Calculates the value of the current Item by multiplying its price (retrieved using itemManager.getItemPrice()) with its quantity.

  1. Check Tradeability and Non-Zero Value:
   final ItemDefinition itemComposition = getItemDefinition(i.getId());
   if (!itemComposition.isTradeable() && value == 0)
   {
       // ...
   }
   else
   {
       // ...
   }

Checks if the current item is not tradeable and its calculated value is zero. If both conditions are true, it recalculates the value using the item’s price from its definition (itemComposition.getPrice() * i.getQuantity()) and adds the item to a priceMap.

  1. Check for Positive Value and Add to priceMap:
   else
   {
       // ...
   }

If the item is tradeable or has a non-zero value, it checks the item ID is greater than zero and the calculated value is larger than zero. When both conditions are true, it adds the item to the priceMap with its calculated value.

  1. Update Wealth:
   wealth += va

Adds the calculated value of the current item to the total wealth.

  1. Return Result:
   return Integer.parseInt(QuantityFormatter.quantityToRSDecimalStack(priceMap.keySet().stream().mapToInt(Integer::intValue).sum()));

Converts the sum of all values in the priceMap to a decimal formatted string using QuantityFormatter.quantityToRSDecimalStack() and then parses it as an integer. This integer value is returned as the result of the method.

osrs plugin total risk and most valuable item in panel

The code calculates the total wealth based on the prices and quantities of items, taking into account tradeability and handling special cases where an item might not be tradeable or have a zero value. The result is formatted as a decimal string.

PvpUtil Java Class Code

https://github.com/slyautomation/osrs_pvp_tutorial/blob/main/pvptools/PvpUtil.java

That’s Part 1 finished! Part 2 ready for you! for the panel and osrs plugin classes. Part 3 will be adding auto specing and auto eating functionality. Happy coding!

3 thoughts on “Osrs Plugin Runelite Development: PvP Helper – Part 1

Leave a Reply

Your email address will not be published. Required fields are marked *