Как написать мод для minecraft на java

от admin

Adventures in building a Minecraft mod

Recently, I have been hard at work building Twitch Vs Minecraft, my first ever mod for Minecraft Forge. In this post, I will be showing you how to create your first Minecraft mod using the Forge API for Minecraft 1.12.2, and I will answer some of the most commonly asked modding questions with full code.

Before reading, make sure you have some basic knowledge of Java. Some Java tutorials will be linked below.

DISCLAIMER: THIS TUTORIAL CODE WILL NOT WORK IN VERSIONS ABOVE 1.12.2, AND HAS NOT BEEN TESTED WITH ANY VERSION BELOW.

Getting Started

First, you will need to head over to the Minecraft Forge Website and download the recommended MDK version. Once you have the zip file, extract it into a folder. Next, open a terminal in that folder and type the following command:

If you’re using Eclipse, you will then want to type:

to generate the correct files. If you’re using IntelliJ IDEA (which is highly recommended), you can instead import the build.gradle file as a project.

You will then want to run:

This can also be found in the Gradle tab on the right of the screen.

When moving over to IDEA from Eclipse, follow the above steps and then run cleanEclipse from the Gradle tab to remove all of Eclipse’s files.

The Example Mod

When you first set everything up, you will be given an example mod. It is located in com.examplemod.examplemod . Here’s what that looks like:

While you most likely want to delete this, it’s a good example of how to create a main class.

Build.gradle

This file contains details such as your mod’s name, package name, author name, and version. You will need to change these values:

Here’s an example taken from Twitch Vs Minecraft:

Remember, the archivesBaseName property needs to be the same as the last part of the group property.

Mcmod.info

This file is no longer found in newer versions of the MDK, and is instead replaced with mods.toml. However, for this tutorial we are using 1.12.2.

This file also contains information for your mod, specifically the info that is displayed in the Mods menu in-game. This page tells you everything you need to know about using this file.

Running the mod

While making your mod, you will want to be able to run it. To do this, click the Debug icon with the runClient configuration enabled. You can alternatively run the game from a terminal, or use the Run option rather than debugging.

While changed classes are automaitcally reloaded when debugging in Eclipse, IntelliJ IDEA doesn’t have this by default.

To enable Reloading changed classes using a keyboard shortcut, go to File -> settings and search for “keymap” when in the keymap menu, search for “Reload” and find “Reload changed classes”, which is located under “Run”. I personally have this bound to ctrl + alt + r . While this may not always work, it helps when making quick edits to your mod.

When loading into a game, you will be logged in as a random username. You can set it up to use your Minecraft account, but this is not recommended, as it can cause security issues, and is usually not needed.

Creating a main class — Forge events

So now we need to create our main class. As a starting point, you can use the example mod shown earlier. The FMLInitializationEvent happens when the mod is loading, so we will see the output somewhere around the main menu. There is also the FMLpreInitializationEvent event, which as the name implies, is called before the Initialization event.

The Pre-Initialization event is used for setting up the Logger. This is useful for outputting information to the console. The event can also be used for loading Config Files. Here’s an example of what that looks like:

ConfigManager appears later in the tutorial.

To use the logger, we will use:

You can also make the logger output warnings and errors.

The ServerStarting event is used to register commands. Here’s an example:

Creating a command

Let’s create our own command that we can register from our main class just like that one. First of all, we’ll create a package called command. This is just a standard way of keeping things neat and easy to access. We then create a class called TutorialCommand and extend it from CommandBase by adding extends CommandBase to the end of our public class TutorialCommand .

Now we want to create a list of aliases: private final List aliases; . To use the list of aliases, add this code:

This piece of code adds the alias “tut” to our command. But we don’t have a default command name yet. Next, we will add this:

This is the default command. Now, the player is able to type either “/tut” or “/tutorial” in chat to use the command. However, if the user uses the command wrong, we will want to output an error. To do this, use:

Next, we want to register the aliases we added earlier, so we add:

(This code won’t change for you — every command has this.)

Next up is checkPermission. You can use this to determine who is allowed to use your command, or if it is considered a “cheat”. To let everyone use your command in any gamemode, use:

You can play around with the value it returns yourself, and see what you like best.

Now, we can add Tab Completions. This essentially works like AutoCorrect, where the player presses tab to finish typing an argument, or get a list of all the arguments they could use.

This code will use a list called autocomplete to get its corrections, but we haven’t created that yet. We can add that just underneath our private final List aliases; as

You will need to replace the arguments with your own. You can have as many of these as you like, just continue adding values to the list.

Now, for the real meat of the command: the execute event. This is where whatever code you want to execute when your player uses your command goes. Here’s how you implement it:

You can check for arguments to, by using this if statement:

You can also replace .equals() with .equalsIgnoreCase() if you don’t want your command to be case-sensitive.

You can also use sender.sendMessage() to reply to a command, like this:

TextFormatting is used here to change the colour of the text in the chat.

Creating blocks and items

For this section, there is a really nice YouTube tutorial by Harry Talks. Click Here to watch it. Both blocks and items are covered by the video. You can also check the links below for written tutorials.

Creating a GUI Overlay

GUI overlays appear on the player’s screen, but don’t enable the mouse. Think of them as custom HUD elements.

To get started with creating one, I will create my TutorialOverlay class inside a package called gui . Here’s what the class will look like:

This code renders the text “Hello world!” in dark red in the top left corner of the screen. Replace condition goes here with a valid boolean to be able to enable and disable the GUI.

Creating a GUI Screen

GUI Screens are like Overlays, but the mouse is enabled and the player can interact with the GUI. An example of this is the game’s pause menu.

First, we start off by extending our class from GuiScreen .

Now we need to set some variables:

We can change if the GUI pauses the game in Singleplayer mode by changing this code:

We can add buttons to our Button List for use later on, as seen here:

This button will close our GUI.

Now we need to create our drawScreen event. This GUI opens a box with a message that wraps around, and has a button that closes the GUI. The variable message will need to be set beforehand, and I do this from whatever class actually opens the GUI, hence why it is public and static.

Читать:
Почему не работает 0 на боковой клавиатуре ноутбука

drawDefaultBackground draws the transparent grey background seen in every GUI screen in Minecraft. width and height refer to the width and height of the game window, which in fullscreen for me is 1920×1080. By dividing the width and height by 2, we get the center of the screen. This is then adjusted for the texture, because otherwise the top-left corner would be in the center, rather than the actual center of the image. 4210752 is the colour code used for GUI screen titles in Minecraft. super.drawScreen is used to essentially loop this funtion until displayGUI is false.

Now let’s make our button functional:

When the button is clicked, it sets a boolean called displayGUI to false, and in the drawScreen function we say that if the variable is false, we close the screen.

The background image I used for the GUI (“textures/gui/messagebox_background.png”) can be found here. It is based on the Crafting Table GUI.

Creating a custom crafting recipe

To create a custom crafting recipe, you want to first go to your resources folder (usually src/main/resources) and create a folder named recipes. Create a json file with whatever name you want, but make it something sensible and memorable, like your item name followed by the word “recipe”. Then, head over to this website and copy and paste the output json into your blank json file. because we are using 1.12.2, some items, blocks and crafting methods, for example the Stonecutter and Blast Furnace are unavailable. Make sure you only use what is available in your Minecraft version.

If you want your crafting recipe to make a custom item, you can use a placeholder item. For example, I will make the output of my crafting recipe on the website TNT, and then replace where it says minecraft:tnt in the output json to tutorialMod:tutorialItem .

Config files

Configuration files are stored in the config folder, as <modname>.cfg . To save and load a configuration file, we will create a ConfigManager class. I am creating under the package util .

Here’s what it should look like:

Now we will replace properties go here with our properties. Properties are how variables are stored inside the file.

Paste this property inside both the loadConfig() and saveConfig() functions. Underneath it in loadConfig , we will add:

Here, our tutorialVariable is part of another class, called tutorialClass . Because our variable is a string, we use .getString() to return the value. You can also use .getInt() , .getBoolean() etc. depending on the data type.

Now we move on to saving to the config file. Underneath our property in saveConfig() , we will set our property to the value of tutorialClass.tutorialVariable — the reverse of what we just did in loadConfig() .

It’s really that simple! We can call saveConfig() from other classes — this is best done using a command.

Building the mod

So, you have now tested your mod thoroughly, it works great, and you are happy with it. But you want to be able to upload the mod to CurseForge, or another similar website. To build your mod’s Jar file, use the following command in your project’s root directory:

You can also run this from the Gradle tab in IntelliJ IDEA.

This will generate two files: one is your mod’s Jar, and another has the same name, but with “-sources” on the end. The sources file is not a mod! You can ignore and/or delete this file.

HybridEidolon / 01-guide.md

Make sure you have Gradle installed and in your path, so you can run it from command line. Otherwise, you should copy a bootstrapper and the gradle jar into your project.

Use this template build.gradle (for the MC 1.8 unstable branch) for your gradle script:

Save this in a new directory and run gradle setupDecompWorkspace and gradle build to set everything up on your local cache. Gradle will be smart and not have multiple copies of this cache if you are working on multiple mods with the same target MC version.

Replace version and mappings in the minecraft block to change the MCF version your mod targets, as well as the obfuscation mappings from MCP to use. You do not need mappings if you are using a stable build.

You can uncomment the processResources block and extend it as necessary to provide build-time substitution to your mcmod.info file (which should go in src/main/resources). A template for mcmod.info is as follows:

And a hello world template MyModMain.java for your mod class:

You can generate IDE project files with gradlew idea for IntelliJ and gradlew eclipse for Eclipse.

Создание модификаций с помощью Forge

В этой статье описывается процесс создания модификаций для Minecraft с использованием API Forge и Eclipse. Для создания даже простых модификаций требуется знание основ Java. Если во время создания модификаций возникнут вопросы или проблемы, не описанные здесь, опишите их на странице обсуждения.

Таблица готовности
Урок 1.6+ 1.7+ 1.9+ 1.10+ 1.12+ 1.14+
Блок Готов Готов Готов Готов Готов Не планируется
Предмет Готов Готов Готов Готов Приостановлено Не планируется
Крафт Готов Готов Готов Готов Приостановлено Не планируется
Компиляция Готов Готов Готов Готов Приостановлено Не планируется
Генерация Возможно Готов Готов Не планируется Приостановлено Не планируется
Прокси и инстанция Не планируется Готов Не планируется Не планируется Приостановлено Не планируется
Моб Возможно Готов Не планируется Не планируется Не планируется Не планируется
Блоки с моделью Возможно Возможно Не планируется Не планируется Приостановлено Не планируется
Доп. Уроки Всего: 3 Всего: 12 Всего: 10 Всего: 0 Всего:0 Всего:0

Общие сведения

Для создания модификаций в любом случае нужны JDK и Eclipse. Первая — это комплект разработчика Java и отличается от обычной Java тем, что имеет средства для компиляции/декомпиляции, несколько дополнительных библиотек и документацию. С 2019-го года ввиду изменений в лицензировании для загрузки JDK потребуется учётная запись Oracle. Также важно то, что Minecraft 1.12 не поддерживает Java ниже 7-й и выше 9-й включительно, тогда как 1.14 поддерживает практически все версии Java выше 8-го выпуска. Eclipse — это среда разработки, которая имеет поддержку синтаксиса нужного языка программирования, а также в ней был написан сам Minecraft.

Создание модов для Minecraft 1.15-1.17 [Forge/Fabric]

Привет всем! Одним из моих первых увлечений после начала изучения языков программирования был Minecraft. Вернее его моддинг. Поиграть тоже было круто, но иногда были шикарные идеи, которые были просто необходимы этой игре! Тем более версии 1.2.5, если кто такую помнит. Но тогда как-то вообще не понимал, что я делаю, а потому и интерес со временем угас.

Спустя время я снова столкнулся с этой игрой (спасибо младшему брату -_-) и вспомнил былые увлечения. Это был уже Minecraft 1.12 или вроде того. Конечно же новые знания позволили сделать куда больше, но по правде некоторые вещи выходили наугад (как бывает у всех прогеров :D).

Короче, как вы все, конечно же, догадались — тут то я решил и сам гайд написать. Ведь что-то таки могу, да и актуальных материалов на русском оказалось не так и много. Возьмем даже офф. вики:

Что-то не пошло…

Опыт может не так велик, но постараюсь расписать и описать все как можно понятнее. Так же буду рад любым подсказкам и замечаниям ^_^

Список статей о моддинге Minecraft 1.15-1.16

UPD 27.04.20: Немного меняю иерархию статей. Теперь не будет номеров вроде Первый урок, второй и т.д. С этого момента уроки будут разделены по группам. Думаю, что так будет логичнее и проще. И да, некоторые статейки теперь нужно будет поправить, чем я и займусь в ближайшие дни.
UPD 09.07.20: Начал обновлять гайды для соответствия версии 1.16.1.
UPD 14.07.21: Жду выхода Forge 1.17, а после этого обновлю все статьи!
UPD 22.08.21: Начал публиковать новые гайды по Froge 1.17.1!

Похожие статьи