Home > Articles > Home & Office Computing > Entertainment/Gaming/Gadgets

Create a Minecraft Mod with the Spigot API

  • Print
  • + Share This
Mods are special Java programs that run on a Minecraft server. They can’t be run anywhere else. Writing a mod requires the use of the Spigot API, a set of Java programs that do all of the background work necessary for the program to function inside a Minecraft game. This chapter from Absolute Beginner's Guide to Minecraft Mods Programming, 2nd Edition demonstrates how a mod is created.
This chapter is from the book

Now that you have a Spigot server for Minecraft set up and running and have installed the NetBeans integrated development environment (IDE), you’re ready to create and deploy a mod.

Mods are special Java programs that run on a Minecraft server. They can’t be run anywhere else.

Writing a mod requires the use of the Spigot API, a set of Java programs that do all of the background work necessary for the program to function inside a Minecraft game. A Java program also is called a class, so the Spigot API is called a class library.

The Spigot class library handles things like determining the (x,y,z) location of any object in the game, including a player. Everything you interact with in the game is represented in Spigot.

Before this book takes a full trip through Java, from the basics of the language into advanced features, this chapter demonstrates how a mod is created. This will give you a chance to see where all this material is headed. Many programming concepts will be unfamiliar to you, but all will be fully explained in subsequent chapters.

Creating Your First Mod

Mods are packaged as Java archive files, also called JAR files. NetBeans, the free integrated development environment from Oracle used throughout this book, automatically creates JAR files every time you build a project.

When you have finished writing a mod, you will be storing it under the server’s folder in a subfolder named plugins.

The mod you are creating is a simple one that demonstrates the framework you’ll use in every mod you create for Spigot. The mod adds a /petwolf command to the game that creates a wolf mob, adds it to the world, and makes you (the player) its owner.

Each mod will be its own project in NetBeans. To begin this project, follow these steps:

  1. In NetBeans, select the menu command File, New Project. The New Project Wizard opens.
  2. In the Categories pane, select Java, and in the Projects pane, select Java Application. Then click Next.
  3. In the Project Name field, enter PetWolf (with no spaces and capitalized as shown).
  4. Click the Browse button next to the Project Location field. The Select Project Location dialog appears.
  5. Find the folder where you installed the Minecraft server. Select it and click Open. The folder appears in the Project Location field.
  6. Deselect the Create Main Class check box.
  7. Click Finish.

The PetWolf project is created, and two folders appear in the Projects pane, Source Packages and Libraries, as shown in Figure 3.1.

FIGURE 3.1

FIGURE 3.1 Viewing a project in the Projects pane.

On each mod project, you must add a Java class library before you begin writing Java code: the Spigot server’s JAR file, which includes the Spigot API. Here’s how to do this:

  1. In the Projects pane, right-click the Libraries folder and select the menu command Add Library. The Add Library dialog opens.
  2. Click the Create button. The Create New Library dialog appears.
  3. In the Library Name field, enter Spigot and click OK. The Customize Library dialog opens.
  4. Click the Add JAR/Folder button. The Browse JAR/Folder dialog opens.
  5. Use the dialog to find and open the folder where you installed the server. You see a file in that folder named spigotserver.
  6. Click that file.
  7. Click Add JAR/Folder.
  8. Click OK.
  9. In the Add Library dialog, the Available Libraries pane now has a Spigot item. Select it and click Add Library.

The Projects pane now contains the JAR file for the Spigot API in the Libraries folder, so you’re ready to begin writing the mod program.

Follow these steps to create the program:

  1. Click File, New File. The New File wizard appears.
  2. In the Categories pane, select Java.
  3. In the File Types pane, select Empty Java File; then click Next.
  4. In the Class Name field, enter PetWolf.
  5. In the Package field, enter com.javaminecraft.
  6. Click Finish.

The file PetWolf.java opens in the NetBeans source code editor.

Before you begin entering any code, this section explains the basics of how a mod is structured. Don’t type in anything yet.

Every mod you create for Spigot begins with a framework of standard Java code. Here’s the main part of that code, customized in a few places for this project:

public class PetWolf extends JavaPlugin {

    public static final Logger LOG = Logger.getLogger(

        "Minecraft");



    public boolean onCommand(CommandSender sender,

        Command command, String label, String[] arguments) {



        if (label.equalsIgnoreCase("petwolf")) {

            if (sender instanceof Player) {

                // do something cool here

                LOG.info("[PetWolf] Howl!");

                return true;

            }

        }

        return false;

    }

}

Looking at this framework, the only things that will change when you use it for a different mod are the three things that refer to PetWolf because those are specific to this project:

  • The name of the program is PetWolf.
  • The argument inside label.equalsIgnoreCase("petwolf") is the command the user will type in the game to run the mod. This program implements the command /petwolf (commands in a mod are preceded by a slash (/) character). The label object, which is sent as an argument to onCommand(), is a string that holds the text of a command entered by the user.
  • The statement that calls log.info("[PetWolf] Howl!") sends a log message that is displayed in the Minecraft server window.

Everything a mod does when its command is entered goes at the spot marked by the comment // do something cool here. Comments are messages in a program that explain what it does to humans reading the code. They’re ignored by the computer when the program runs.

The first thing the PetWolf mod needs to do is learn more about the game world, using these three statements:

Player me = (Player) sender;

Location spot = me.getLocation();

World world = me.getWorld();

A Player object called me is the character controlled by the person playing the game.

With this Player object, you can call its getLocation() method to learn the exact spot where the player is standing. A method is a section of a Java program that performs a task. Here, the method retrieves the player’s current location as a Location object. Three things you can learn about a location are its (x,y,z) coordinates on the three-dimensional game map.

The Player object has a getWorld() method that responds with the World object that represents the entire game world.

Most of the mods you create need these three Player, Location, and World objects.

This mod creates a new mob that’s a wolf, using the spawn() method of the World object:

Wolf wolfie = world.spawn(spot, Wolf.class);

There’s a class for every type of mob in the game. The two arguments to the spawn() method are the location where the wolf should be placed and the class of the mob to create.

This statement creates a Wolf object named wolfie at the same spot as the player.

The color of the wolf’s collar is set in this statement:

cat.setCollarColor(DyeColor.PINK);

After the wolf has been created, the player becomes its owner by calling the wolf’s setOwner() method with the Player object me as the only argument:

wolf.setOwner(me);

Now you can begin typing. Put all this together by entering Listing 3.1 into the source code editor and clicking the Save All button in the NetBeans toolbar (or select File, Save).

LISTING 3.1 The Full Text of PetWolf.java

 1: package com.javaminecraft;

 2:

 3: import java.util.logging.*;

 4: import org.bukkit.*;

 5: import org.bukkit.command.*;

 6: import org.bukkit.entity.*;

 7: import org.bukkit.plugin.java.*;

 8:

 9: public class PetWolf extends JavaPlugin {

10:     public static final Logger LOG = Logger.getLogger(

11:         "Minecraft");

12:

13:     public boolean onCommand(CommandSender sender,

14:         Command command, String label, String[] arguments) {

15:

16:         if (label.equalsIgnoreCase("petwolf")) {

17:             if (sender instanceof Player) {

18:                 // get the player

19:                 Player me = (Player) sender;

20:                 // get the player's current location

21:                 Location spot = me.getLocation();

22:                 // get the game world

23:                 World world = me.getWorld();

24:

25:                 // spawn one wolf

26:                 Wolf wolf = world.spawn(spot, Wolf.class);

27:                 // set the color of its collar

28:                 wolf.setCollarColor(DyeColor.PINK);

29:                 // make the player its owner

30:                 wolf.setOwner(me);

31:                 LOG.info("[PetWolf] Howl!");

32:                 return true;

33:             }

34:         }

35:         return false;

36:     }

37: }

The import statements in Lines 3–7 of Listing 3.1 make five packages available in the program: one from the Java Class Library and four from Spigot. Packages are groups of Java classes that serve a related purpose. For instance, the org.bukkit.entity package referenced in Line 6 is a group of classes for the mobs in the game (which in Spigot are called entities).

The return statements in Lines 32 and 35 are part of the standard mod framework. A method in Java can return a value when its task is completed. Your mods should return the value true inside the onCommand() method when the mod handles a user command and false when it doesn’t.

You have created your first mod, but it can’t be run yet by the Spigot server. It needs a file called plugin.yml that tells the server about the mod.

This file is a YAML file, which you also can create with NetBeans using these steps:

  1. Select File, New File. The New File dialog opens.
  2. In the Categories pane, scroll down and select Other.
  3. In the File Types pane, select YAML File and click Next.
  4. In the File Name field, enter plugin. (Don’t put .yml on the end; this is done for you by NetBeans.)
  5. In the Folder field, enter src.
  6. Click Finish.

A file named plugin.yml opens in the source code editor with two lines in it:

## YAML Template.

---

Delete these lines. They aren’t needed in this file. Enter the text of Listing 3.2 into the file, and be sure to use the same number of spaces in each line. Don’t use tab characters instead of spaces.

LISTING 3.2 The Full Text of This Project’s plugin.yml

 1: name: PetWolf

 2:

 3: author: Your Name Here

 4:

 5: main: com.javaminecraft.PetWolf

 6:

 7: commands:

 8:     petwolf:

 9:         description: Spawn a wolf as the player's pet.

10:

11: version: 1.0

Replace Your Name Here with your own name. Telling people you wrote a mod is the first step toward becoming a legendary Minecraft coder.

To double-check that you have entered the spaces correctly, there are four spaces in Line 8 before the text petwolf and eight spaces in Line 9 before description.

The plugin.yml file describes the mod’s name, author, Java class file, version, command, and a short description of what the command does.

This file must be in the right place in the project. Look in the Projects pane, where it should be inside the Source Packages folder under a subheading called <default package>. This is shown in Figure 3.2.

FIGURE 3.2

FIGURE 3.2 Checking the location of plugin.yml.

If the plugin.yml file is in the wrong place, such as under the com.javaminecraft heading, you can use drag and drop to move it to the proper location. Click and hold the file, drag it to the Source Packages folder icon, and drop it there.

You’re now ready to build your mod. Select the menu command Run, Clean and Build Project. If this is successful, the message Finished Building PetWolf (clean, jar) will appear in the lower-left corner of the NetBeans user interface, way down at the bottom edge.

The mod is packaged as a file called PetWolf.jar in a subfolder of the project. To find it, click the Files tab in the Projects pane, expand the PetWolf folder (if necessary), and then expand the dist subfolder. The Files tab lists all the files that make up the project, as shown in Figure 3.3.

FIGURE 3.3

FIGURE 3.3 Finding the PetWolf mod’s JAR file.

This PetWolf.jar file needs to be copied from the project folder to the Minecraft server. Follow these steps:

  1. If the Minecraft server is running, stop it by going to the server window and typing the command stop; then press the spacebar or any other key to close that window.
  2. Outside of NetBeans, open the folder where you installed the Minecraft server.
  3. Open the PetWolf subfolder.
  4. Open the dist subfolder.
  5. Select the PetWolf file (a JAR file), and press Ctrl+C to copy it.
  6. Go back to the Minecraft server folder.
  7. Open the plugins subfolder.
  8. Press Ctrl+V to copy PetWolf into it.

You have deployed your new mod on the Minecraft server. Start the server the same way you did before—by clicking the start-server.bat file you created. If you look carefully at the messages that display in the server window as the server loads, you see two new messages in the log file that display as it runs:

[PetWolf] Loading PetWolf v1.0

[PetWolf] Enabling PetWolf v1.0

These messages do not appear together. One appears close to the top and another close to the bottom.

If you don’t see these messages, but instead see some long, complicated error messages, double-check everything in PetWolf.java against Listing 3.1 and plugin.yml against Listing 3.2 to ensure they were entered correctly; then rebuild and redeploy the mod.

After you run the Minecraft client and connect to your server, enter the command /petwolf. You now have a new wolf who will follow you around. Enter the command as many times as you like to keep adding wolves.

Figure 3.4 shows me and 20 wolves. Hostile mobs don’t last long against us. We will rule this world. Hoooooooooooooooooowl!

FIGURE 3.4

FIGURE 3.4 Your own wolf pack, courtesy of your own mod.

  • + Share This
  • 🔖 Save To Your Account

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020