Home > Articles > Certification > Microsoft Certification

This chapter is from the book

Creating a Basic Item

It’s time to start creating your own item. To get started, you start in your mod file. Just below the two String variables and just above the init method, create a new method called preInit. The parameter for this method must be FMLPreInitializationEvent. Don’t forget to add the @EventHandler annotation above the method, or your item won’t work without showing any errors. Once you have done that, the file should look like Listing 4.1.

LISTING 4.1 Mod File with preInit Method

package com.wuppy.samsmod;

import net.minecraft.enchantment.Enchantment;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraft.util.WeightedRandomChestContent;
import net.minecraftforge.common.ChestGenHooks;
import net.minecraftforge.common.DungeonHooks;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.Mod.EventHandler;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.registry.GameRegistry;

@Mod (modid = SamsMod. MODID, version = SamsMod. VERSION)
public  class SamsMod

{
     public static final String MODID = “wuppy29_samsmod”;
     public static final String VERSION = “1.0”;

     @EventHandler
     public void preInit(FMLPreInitializationEvent event)
     {

     }

     @EventHandler
     public void init(FMLInitializationEvent event)
     {
         //Recipes
         GameRegistry.addRecipe(new ItemStack(Items.apple),
                “XXX” ,
                “XXX” ,
                “XXX” ,
                “X” , Blocks.leaves
         );
         GameRegistry.addRecipe(new ItemStack(Items.arrow),
                “YZ” ,
                “X ” ,
                “X” , Items.flint , “Y” , Items.stick, “Z” , Blocks.leaves
         );
         GameRegistry.addShapelessRecipe(new ItemStack(Items.dye, 2, 1),
                 Items.redstone, new ItemStack(Items.dye, 1, 1)
         );
         GameRegistry.addSmelting(Blocks.stone, new ItemStack(Blocks.stonebrick), 0.1F);

         ItemStack enchantedSwordItemStack = new ItemStack(Items.stone_sword);
         enchantedSwordItemStack.addEnchantment(Enchantment.sharpness, 1);

         GameRegistry.addShapelessRecipe (enchantedSwordItemStack,
                         Items.flint, Items.stone_sword
         );

         //Dungeon changes
         DungeonHooks.removeDungeonMob(“Spider” );
         DungeonHooks.addDungeonMob(“Creeper” , 100);
         ChestGenHooks.removeItem(ChestGenHooks.DUNGEON_CHEST, new ItemStack(Items.saddle));
         ChestGenHooks.addItem(ChestGenHooks.DUNGEON_CHEST, new WeightedRandomChestContent(new ItemStack(Blocks.cobblestone), 25, 50, 10));
     }
}

There are three initialization phases with Forge: PreInit, Init, and PostInit. PreInit is where you register all the basics for your mod. Init is where you place mod-specific code that is not directly related to registering. Recipes should also go in Init. PostInit is where you add code that interacts with other mods.

This forces modders to do all those things at the same time, making it easier for other modders who create mod bridges or other application programming interfaces (APIs) to use a later initialization phase to find out which blocks are added or which mods are installed.

Because of these rules, you need to create the preInit method for the registry of items.

To create an item, you first must create a new variable. This is a variable that will likely be used in several files. Therefore, it must be public and static. It must also be placed outside of any methods in the class, just below the two String variables used in the @Mod line. Because you are going to create an item, the variable should be an item. The name for the variable can be anything you want, but best practice is to give it the name of the item.

In this book, the basic item you create is a key for the dungeon created over the course of this book. The variable line should look like this:

public static Item key ;

If you are getting an error under item, import the Item class from the Minecraft package. Be certain to get the one from the Minecraft package, or you will get a lot of errors in the following code.

In the preInit method, two lines of code are required to make most items. One line is to let Java know what the key object actually is, and the other line is to tell Forge to register it as an item. The following code snippet shows the code for the key. Note that the code contains an error, which you fix shortly.

key = new ItemKey();

GameRegistry.registerItem(key, “Key”);

The top line sets key to a class, which you create in a few minutes. It can also be called anything you want, but the general name for it is Item followed by the item name. Having an error under the ItemKey, or whatever your name for it is, is normal. It’s because ItemKey is a class that isn’t created yet. From now on, this line will be called the item init line.

The second line of code registers an item to Forge using the GameRegistry file, which makes sure Minecraft knows the item exists and can be used. The method used this time is registerItem, which takes two parameters. The first parameter is an Item object and the second parameter is a name for it. The name can also be anything you want, but the best way to name it is the name of the item. It’s important to make sure that there aren’t any duplicate names in the item registry. If there is another item called Key, it might not work. However, Forgeautomatically adds the modid in front of the name you use to register here. This ensures that multiple mods can have an item called Key without problems. If item registry line is mentioned in this book, it references this line.

The following code shows the preInit method and the new variable after adding the item. All the other code in the file is the same, except for a few new imports:

public static Item key;

@EventHandler
public void preInit(FMLPreInitializationEvent event)
{
    key = new ItemKey();

    GameRegistry.registerItem(key, “Key”);
}

Creating an Item File

To fix the error under the class name in the item init line, you create an item file with the name used in the init line. To create a file like that, hover your mouse over the error and click Create Class ‘...’. This causes the New Java Class window to open. In this window, click Finish. You will now have a file that should look like Listing 4.2.

LISTING 4.2 Empty Item File

package com.wuppy.samsmod;

import net.minecraft.item.Item;

public class ItemKey extends Item
{

}

To make a fully functional item, you must add a constructor to this file. A constructor is a method without a return type and the method name has to be exactly the same as the class file. A constructor is a special method in Java that is used to create an object for a class. This method will run whenever the Item object is created. An empty constructor for ItemKey will look as follows:

public ItemKey()
{

}

There must be two lines of code in this constructor for Minecraft to recognize it as an item and actually use it. The first line makes sure the item has some sort of name:

setUnlocalizedName(SamsMod.MODID + “_” + “key”);

This sets the unlocalized name of the item to something. An item requires an unlocalized name, or it will not show up anywhere. Without a name, it isn’t an item. It’s important to make sure that the unlocalized name is unique for every item in every mod. To make sure this happens, use the modid of your mod followed by an underscore and then finally the name of the item variable in your mod file. This ensures that there can’t possibly be duplicates, because a modid has to be different for every mod installed, and you can’t have two variables with the same name.

When you have an item, it doesn’t automatically show up in the Creative menu. This is quite useful because not everything should be on one of the Creative tabs. However, in the case of most items, you want it to be visible somewhere. To do that, you will need the following code:

setCreativeTab(CreativeTabs.tabMisc);

This method requires a single parameter, which is a CreativeTab. To get the correct CreativeTab, you might want to look through the file in which all of the tabs are listed. ItemKey will be added to the Miscellaneous tab.

If you start the game right now, you will see there is an item in the Creative menu with a weird black and purple texture. The name is also strange.

Fixing the Name

To fix the names of an item, you have to add a localization for it. By default, items in Minecraft have the name item.unlocalizedname.name. This is not a desirable name and should almost always be changed. You do this by adding localizations. Minecraft has different localizations for every language. If you play Minecraft with a localization different than en_US, which is the default American English, it first tries to look for localizations under that language. If it doesn’t find them, it tries to get them from the en_US ones. If it can’t find them there either, the default name is used.

Fixing the name of the item is going to be quite a bit of work. First, navigate to the forge folder created in Hour 1, “Setting Up the Minecraft Development Environment.” Then enter src/main/resources . Figure 4.1 shows the correct folder structure.

FIGURE 4.1

FIGURE 4.1 The folder structure for resources.

In this folder, you need to create a few custom folders. The first folder is called assets. Within the assets folder, you need to make another folder with the name of your modid, which has to be the same as the MODID variable in your mod file. The final folder you need to create is called lang. If you now go into your Eclipse, you should see a white package with the names you just used under the resources folder. In the case of the mod written in this book, the folder structure is assets/wuppy29_samsmod/lang. It should look similar to Figure 4.2.

FIGURE 4.2

FIGURE 4.2 The folder structure for lang.

Once you are certain the folder structure is correct, you need to add a new file. The file should be called en_US.lang.

Open the file using a text editor of your choice. If you look at the name of the item in the game, it’s item.UnlocalizedName.name. The .lang file created is used to add a localized name for the item. To create a localized name for the key, you need the following line in the .lang file:

item.wuppy29_samsmod_key.name=Key

The first part is the name of the item when displayed without localizations. After that, add an equal sign and then add the name on the other side. Ensure there are no spaces between the unlocalized name, the equal sign, and the localized name. If there are, it will either not work or look strange. You can have spaces in the unlocalized and localized names themselves in this file.

Now when you start the game and take a look at the item you created, the name will be fixed.

Adding a Texture

To fix the strange purple texture on the item, you must do a few things. First, you must actually create the new item texture. It is outside the scope of this book to cover exactly how to create the best textures, but this section does cover the basics. You need the image editor software of your choice, such as GIMP, Photoshop, or Paint. In one of these programs, create a 16×16 pixel image of the item you want. It doesn’t really matter what you put in there. However, what does matter is the file format and filename when you save it. The file format has to be .png. The filename has to be something you can easily use in code. In this book, it will always be the same name as the variable unless specified differently. The item texture used for the key is called key.png and looks like Figure 4.3.

FIGURE 4.3

FIGURE 4.3 The key item texture.

Now that you have a texture for the item, you need to place it somewhere where Forge can find it for you. This place is quite similar to the location of the .lang files. In the forge folder, open the following folders: src\main\resources\assets\wuppy29_samsmod, replacing the wuppy29_samsmod part with the modid of your mod. The path should look similar to Figure 4.4.

FIGURE 4.4

FIGURE 4.4 Modid folder structure.

In this folder should be the lang folder you created earlier. This time, create a folder called textures. In that folder, create a final folder called items. Place the texture file you created earlier in there. In the case of the ItemKey, the texture is Figure 4.3. The folder structure for it should look similar to Figure 4.5.

FIGURE 4.5

FIGURE 4.5 Item texture folder structure.

Now the texture is ready to be used. Now, you just need to tell Forge to get that texture for the item. To do this, you add a new line of code to the constructor. It should look like the following:

setTextureName(SamsMod.MODID + “:” + “key”);

The texture name has to be first the modid, which should be stored in a variable in your mod file. Then you need a colon and the unlocalized name of the item.

Right now, the constructor looks like this:

public ItemKey()
{
        setUnlocalizedName(SamsMod.MODID + “_” + “key”);
        setTextureName(SamsMod.MODID + “:” + “key”);
        setCreativeTab(CreativeTabs.tabMisc);
}

Once you have added this line of code, your item will work. Figure 4.6 shows the key in the game.

FIGURE 4.6

FIGURE 4.6 The ItemKey in Minecraft.

This file isn’t coded very well because the same String is used twice. If you want to change the name of the item, you must change the name in both locations. To make this a little bit easier, create a private String that contains key. Then put the String variables in these methods.

After completing the Try It Yourself activity and all other tasks in this hour, the whole item file should look like Listing 4.3.

LISTING 4.3 Finished ItemKey File

package com.wuppy.samsmod;

import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;

public class ItemKey extends Item
{
        private String name = “key” ;

        public ItemKey()
        {
                setUnlocalizedName(SamsMod.MODID + “_” + name);
                setTextureName(SamsMod.MODID + “:” + name);
                setCreativeTab(CreativeTabs.tabMisc);
          }
}

Now when you launch the game, you should see the item with the correct name and the correct texture.

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