BukkitWiki

Welcome to the BukkitWiki!

This Wiki is home to Bukkit's documentation and regulations surrounding the Bukkit Project and it's services. Want to help out? We would love to have you! Signup to get started!

READ MORE

BukkitWiki
Register
Advertisement
TODOIcon
Working on it...

This page is a work in progess, check back regularly for more content!

Вступление

Статья базируется на уроке от Adamki11s, в нём содержится достаточно большое количество примеров.

После изучения данной статьи мы рекомендуем Вам ознакомиться с дополнительными материалами автора.

Перевод на русский делают ZZZubec и fromgate. Дополняет перевод:D_ART, Xipxop, а также snaypak. Контроль за орфографией, пунктуацией, грамотностью изложения и викифицированием — pashak.

Учим Java

Для создания модов Вам потребуются хотя бы базовые знания языка программирования Java. Для новичков советуем Вам пройтись по следующим ресурсам:

Видеоуроки

  • JavaVideoTutes.com — основы Java.
  • devcolibri.com - Основы Java
  • GTOTechnology — создание плагинов для Bukkit.
  • Dinnerbone — канал одного из основателей Bukkit.
  • Thenewboston — много полезного.

Текстовые учебники

Изучение Java дастся Вам гораздо легче, если вы знаете другие языки програмирования. Также в изучении этого языка могут помочь следующие издания:

  • Герберт Шилдт — «Полный справочник по Java SE6»
  • Брюс Эккель — «Философия Java»

Java IDE

Минимумом для разработки на Java вам являются лишь текстовый редактор и компилятор. Однако гораздо удобнее использовать интегрированную среду разработки — IDE (Integrated Development Environment). Это целый комплекс программных средств, позволяющий писать, компилировать и отлаживать написанные программы.

Наиболее популярными средами для разработки на Java являются:

Eclipse — самая популярная среда, ей пользуется большинство пользователей Bukkit. Если вы новичок в Java, то Eclipse предпочтительнее, так как данная статья написана на примерах именно этой программы. Рекомендуемую версию Eclipse можно взять отсюда.

По мнению автора лучшим руководством для Eclipse является эта статья (англ.). Руководство написано для версии 3.3, но, скорее всего, подойдёт и к более новым версиям.

Также есть руководство (англ.) и для IntelliJ, используемой преимущественно для разработки игр на Java.

Начинаем проект плагина

Создание проекта

Перед тем как мы начнем создавать новый плагин не забудьте настроить "переменные окружения" в Eclipse. Запустите Eclipse и нажмите  File > New > Java Project:

NewJavaProject

Имя проекта может быть каким хотите (но я рекомендую в любые названия вкладывать смысл). Далее следуйте инструкциям. В Package Explorer в левой панели будет отображаться весь проект целиком. ЛКМ на плюсе возле папки с названием проекта, раскроет весь проект и Вы сможете посмотреть все файлы которые относятся к нему.

Добавление Bukkit API к нашему плагину

Перед тем как мы начнем разработку нового плагина, нам необходимо добавить внешнюю библиотеку баккита, в виде JAR. Вы также можете добавить и другие плагины или библиотеки таким же способом.

Последнюю текущую версию баккит сервера Вы можете найти здесь: Bukkit API - Development Snapshot


Кликните "Правой кнопкой мыши" (ПКМ) по нашему проекту и нажмите на Свойства. Далее нажмите на Java Build Path в левой части и в правой части перейдите на закладку Libraries. Нажмите на кнопку Add External JARs, чтобы выбрать jar баккит сервера который Вы скачали.

BuildPathPic

Подключение справки Bukkit для Eclipse

Если Вы обладаете уже опытом работы с Eclipse и Java, то вы наверняка знаете что при наведении мыши на какую либо команду или класс, всплывает подсказка, которая очень помогает при написании кода. Для подключения справки нам понадобиться интернет соединение. Баккит также содержит справку для разработчиков, которая интегрируется в Eclipse. Для того чтобы её подключить необходимо нажать ПКМ по Bukkit jar файлу (который был добавлен в проект), затем выберем в панели слева Javadocs Location, затем справа в адресе укажем "http://jd.bukkit.org/apidocs/"(без кавычек):

Bukkitjavadocs

Нажмите validate (для проверки), а затем OK. Вот и всё! Теперь справка поможет нам в дальнейшем.

Начинаем создавать ваш плагин

Сейчас вы должны создать 'package' (или 'пакет' как я буду называть его далее) в котором будут храниться все файлы классов Java. Правой кнопкой по папке "src" и выберите New > Package:

MakePackage

Имя вашего 'пакета' должно быть таковым: "me.yourname.pluginname" - там где 'yourname' это название пакета и оно не должно содержать Русских букв и слова bukkit.  Например: Если ваш плагин называется "TestPlugin", то 'пакет' должен называться так: "me.adamki11s.TestPlugin".

Теперь наш проект создан, мы можем добавлять файлы классов и начать делать наш плагин. Правой кнопкой по папке "src" и выберите  New > Class. Главный класс должен иметь то же имя, как и плагин! Например: Плагин с именем "TestPlugin", то первый класс должен называться так "TestPlugin".

Сейчас вы создали основной файл и ваш проект. Чтобы bukkit видел ваш плагин, надо добавить plugin.yml файл. Этот файл содержит важную информацию, без него плагин работать не будет! Нажмите правой кнопкой по папке проекта(Не 'src' , а та что самая первая). Выберете New > File. Назовите файл так: "plugin.yml". По умолчанию Eclipse откроет файл plugin.yml в блокноте (Подсказка:  Если вы хотите держать ваше рабочее пространство упорядоченным закройте текстовый редактор и перетащите plugin.yml в главное рабочее пространство (Справа) и вы сможете редактировать файл внутри eclips.) Вот две вещи которые надо добавить; ссылку на ваш главный класс и команды.          

Простой пример plugin.yml  выглядит вот так :

name: <PluginName>
main: <packagename>.<PluginName>
version: <Version Number>

Внимание: Имя пакета часто включает в себя имя плагина, так что не удивляйтесь, если вы видите <pluginname>.<pluginname> в конце второй строки!

onEnable() и onDisable()

Эти функции вызываются когда плагин enabled/disabled (Включен/выключен). По умолчанию плагин будет включаться при запуске сервера и вы можете настроить сообщение которое пишет в консоле при запуске плагина. onEnable() это первое, что выполняется в плагине.

Введение: onEnable() и onDisable()

Создайте методы onEnable () и onDisable () внутри основного класса, созданного в предыдущем разделе:

public void onEnable(){ 

}

public void onDisable(){ 

}

В настоящий момент функция ничего не делает и как вы заметили получаете ошибку. Это потому, что мы должны указать главный класс, откуда начинается "функционал плагина". В верхней части кода измените объявление класса:  


  

Class <classname> {}

 На следующее:

Class <classname> extends JavaPlugin {}

 

После добавления этого кода вы увидите красные линии под ним, говорящие что, что-то не так. Чтобы исправить это, просто наведите курсор мыши на выделенный код и нажмите правую кнопку мыши Import 'JavaPlugin' (org.bukkit.plugin.java).

Import JavaPlugin

 Вывод сообщений при помощи Logger  

Сейчас мы напишем код, который будет выводить сообщения в консоле о статусе плагина (1 раз) Включен/выключен. Сначала мы должны получить объект регистратора, который позволит нам послать выходные данные на консоль. Для этого классе JavaPlugin имеется метод getLogger(). Для удобства можно объявить специальную переменную:

Logger log = getLogger();

Затем внутри onEnable() мы будет отображаться сообщение о том, плагин был включен:

log.info("Your plugin has been enabled.");

Вы можете сделать тоже самое с onDisable(), убедившись, что изменили сообщение. Ваш главный класс должен выглядеть как-то так::

package me.<yourname>.<pluginname>;

import java.util.logging.Logger;
import org.bukkit.plugin.java.JavaPlugin;

public class <classname> extends JavaPlugin {

	Logger log = getLogger();

	public void onEnable(){
		log.info("Your plugin has been enabled!");
	}

	public void onDisable(){
		log.info("Your plugin has been disabled.");
	}
}

Слушатели событий (хуки)

Слушатели событий или хуки, фактически будут самой большой часть в ваших плагинах. Всё что бы не происходило с игроками на сервере можно отловить через них. Игрок поставил блок или игрок убил какого-то монстра, или что-то другое - это всё отлавливается через хук (событий). Перед тем как вы создадите такой хук, Вам надо зарегистрировать его на стороне плагина. Хорошим местом для регистрации хуков, будет то же место где Ваш плагин подключается к серверу (OnEnable). Когда вы зарегистрируете событие(хук), сервер уже будет знать что когда произойдет событие, он оповестит Ваш плагин о нём. Довольно стандартная модель регистрации событий.

Добавление слушателей(хуков)


Информация неактуальна! Сейчас используется упрощенная система слушателей событий!



Чтобы зарегистрировать само событие, нам понадобится Plugin Manager, его можно получить через "окружение".

PluginManager pm = this.getServer().getPluginManager();

Возможно после того как вы запишите этот код, появится красное подчеркивание на слове PluginManager, этого из-за того что мы ещё не импортировали этот класс. Для устранения данной ошибки достаточно поставить курсор на подчеркнутое слово и нажать правой кнопкой мыши. И выбрать импорт(import) класса.

Следующим шагом будет регистрация события. Возьмем например событие, когда игрок изменяет позицию в игре. Запишем в следующей строке

pm.registerEvent(Event.Type.PLAYER_MOVE, playerListener, Event.Priority.Normal, this);

Важно! Достаточно одного файла слушателя на все события одного типа. Например чтобы отлавливать все события игрока, мы должны их зарегистрировать. А затем создать всего один файл слушателя, и уже в нём написать реакцию (функции) на каждое зарегистрированное событие игрока. И по скольку игра не разделяет одного игрока от другого, получается, что мы получим слушатель одновременно на всех игроков и на каждое их событие.Кроме того, нам не обязательно выносить хуки в отдельный файл, при их малом налиичи можно их просто описать в этом же файле (плагина) просто добавив именные функции внутри класса и добавив implements PlayerListener нашему класса плагина.Также я решил отойти(в некоторых местах) от стандартного перевода в хуках, чтобы русскоязычному населению было более понятно о возможностях, которые дают хуки.

Посмотрите на шаблон

private final <YourPluginName>PlayerListener playerListener = new <YourPluginName>PlayerListener(this);

Допустим мы возьмем имя Basic для файла слушателя, тогда запишем вот так:

private final BasicPlayerListener playerListener = new BasicPlayerListener(this);

Эту часть кода необходимо внести в класс плагина(основного)

В таком случае, создаем новый класс с именем(имя на самом деле произвольное, главное чтобы не было пересечений с другими именами) BasicPlayerListener, и за основной класс возьмем PlayerListener. Не забывайте добавлять необходимые импорты классов, чтобы не было красных подчеркиваний. Должно получится вот так:

public class BasicPlayerListener extends PlayerListener{ //Code here }

Теперь Вам необходимо создать функцию которая и будет обработчиком события (хука). Но перед этим создадим переменную которая будет хранить ссылку(индентификатор) на основной класс плагина.

public MyPlugin plugin;

MyPlugin необходимо заменить на имя нашего класса плагина (основного). И запишем в основную функцию класса слушателя передачу(присвоение, получение) этого индентификатора.

public My plugin;

public BasicPlayerListener(MyPlugin instance) {
    plugin = instance;
}

Чтобы правильно обработать событие, Вы должны создать функцию

public void onPlayerMove(PlayerMoveEvent event){
//do whatever you want to happen when a player moves here
}

Баккит автоматически будет вызывать её после того как событие произошло. Поэтому старайтесь не ошибиться в имени функции Для примера (пример не удачный, поправил), событие EntityDamage, будет иметь название функции onEntityDamage( EntityDamageEvent event) также внутри функции можно получить доступ к тому кто "ударил", через

Event e = event.getDamager();

Отсюда да же, можно получить координаты как самого Entity (вплоть до отдельных координат X,Y,Z), так и того кто ударил, через

event.getLocation();

И помните, что каждому типу событий, необходим свой слушатель. На данный момент эта информация не актуальна, используется общий слушатель Listener

для блоков - BlockListener

дла сущностей - EntityListener

для игрока - PlayerListener

Спасибо за то что читаете, мы все стараемся передать вместе с переводом частичку своих знаний

Команды

Метод onCommand()

Теперь Вы знаете как использовать события, но что если Вам нужно обрабатывать команды, посланные игроком? Для этого используется onCommand. Этот код вызывается когда игрок пишет в чат команду, начиная с символа "/". Например ввод "/do something" вызовет код onCommand. В данном случае при вызове ничего не произойдёт т.к. нужно запрограммировать окружение.

Избегайте использования названий команд, используемых стандартым сервером. Так же необходимо следить за уникальностью названия команды. Например: команда "give" уже используется некоторыми плагиными и добавление ещё одной команды с таким же именем сделает ваш плагин несовместимым с этими плагинами.

Метод

'''onCommand'''

всегда должен возвращать булево значение - true или false. Если возвращаемое значение true, то это условно означает о том, что команда выполнена успешно и вызвавшему само по себе ничего не отобразится. Если же возвращаемое значение фелсе, то плагин обратится к параметру команды 'usage:' и выведет содержимое этого параметра пользователю команды, взятое из файла plugin.yml. При использовании метода

'''onCommand'''

необходимо зарегистрировать 4 параметра:

  • '''CommandSender sender'''
    
    - отправитель команды
  • '''Command cmd'''
    
    - команда, которая была использована
  • '''String commandLabel'''
    
    - псевдоним команды, который был использован
  • '''String[] args'''
    
    - массив аргументов команды, например: /hello abc def вернёт массив с abc находящимся в args[0] и def находящимся в args[1], но если значение массива будет не верным - не вернет массив с abc

Установка команд

public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args){
	if(cmd.getName().equalsIgnoreCase("basic")){ // Если игрок ввёл /basic тогда делаем следующее...
		делаемЧто-то
		return true;
	} //Если это произошло, то возвращаем true, иначе функция вернёт false
	return false; 
}

При написании метода

'''onCommand'''

хорошим тоном считается возвращать false в самом конце метода. Возврат false отобразит пользователю команды параметр использования из plugin.yml (смотри выше). В этом случае, если что-то пошло не так, пользователю выведет сообщение-подсказку. Когда метод возвращает значение, любой код, находящийся ниже него, не будет выполнен, за исключением случаев, когда команда return расположена в закрытом условии и не будет достигнута про исполнении кода. Код

'''.equalsIgnoreCase("basic")'''

означает, что при сравнении строк не будет различий между верхним и нижним регистром. Например строки "BAsIc" и "BasiC" обе эквивалентны basic и код в условии будет воспроизведён.

Добавляем команду в plugin.yml

Вы также должны добавить команду в plugin.yml файл. Добавьте следующее в конец plugin.yml:

commands:
   basic:
      description: Пример команды
      permission: <plugin name>.basic
      usage: /<command> [player]

  • basic - Название команды
  • description - Описание команды.
  • permission - This is used by some help plugins to work out which commands to show to the user.
  • usage - Сообщение которое будет отправлено игроку если метод onCommand вернёт false. Пишите так чтобы игрок смог понять как эту команду использовать

Консольные команды против команд Игроков

Вы, возможно, заметили выше параметр CommandSender sender. CommandSender является интерфейсом Bukkit, у которого есть две полезные (для писателей плагинов) реализации Player и ConsoleCommandSender (чтобы быть точным, Player тоже является интерфейсом).

When you're writing your plugin, it's a very good idea to ensure that commands that can be run from the console actually work, and that commands that should only be run as a logged-in player really are only run as a logged-in player. Some plugins simply return if the sender is not a player (i.e. someone tried to use the plugin's commands from the console), even when those commands make perfect sense from the console (e.g. changing the weather on the server).

One way to do this is:

public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
	Player player = null;
	if (sender instanceof Player) {
		player = (Player) sender;
	}

	if (cmd.getName().equalsIgnoreCase("basic")){ // If the player typed /basic then do the following...
		// do something...
		return true;
	} else if (cmd.getName().equalsIgnoreCase("basic2") {
		if (player == null) {
			sender.sendMessage("this command can only be run by a player");
		} else {
			// do something else...
		}
		return true;
	}
	return false;
}

In this example, the command basic can be run by anyone - a logged-in player, or the server operator on the console. But the command basic2 can only be run by logged-in players.

In general, you should allow as many commands as possible to work on both the console and for players. Commands that need a logged-in player can use the mechanism in the example above to check that the CommandSender is actually a player before continuing. Such commands would generally depend on some attribute of the player, e.g. a teleportation command needs a player to teleport, an item giving command needs a player to give the item to...

If you want to get more advanced, you could do some extra checks on your command arguments so that e.g. a teleportation command could be used from the console if and only if a player's name is also supplied.

Использование отдельного класса CommandExecutor

В приведённом выше примере мы просто вставили метод onCommand() в главный класс плагина. Для небольших плагинов, это прекрасно, но если вы пишете что то большое, возможно, имеет смысл разместить метод onCommand() в своём отдельном классе. К счастью, это не слишком сложно:

  • Создайте новый класс в пакете вашего плагина. Назовите его MyPluginCommandExecutor (хотя, конечно, можете заменить MyPlugin на реальное имя вашего плагина). Этот класс должен реализовать интерфейс Bukkit CommandExecutor.
  • В методе onEnable () вашего плагина, вы должны создать экземпляр нового класса для исполнителя команды, а потом вызвать его при помощи getCommand ("basic") setExecutor (myExecutor)., Где "basic" команда, которую мы хотим выполнить и myExecutor экземпляр который мы создали. 

Лучше объяснить на примере:  

MyPlugin.java (главный класс плагина):  

private MyPluginCommandExecutor myExecutor;
@Override
public void onEnable() {
	// ....

	myExecutor = new MyPluginCommandExecutor(this);
	getCommand("basic").setExecutor(myExecutor);

	// ...
}

MyPluginCommandExecutor.java:

public class MyPluginCommandExecutor implements CommandExecutor {

	private MyPlugin plugin;

	public MyPluginCommandExecutor(MyPlugin plugin) {
		this.plugin = plugin;
	}

	@Override
	public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
		// ... implementation exactly as before ...
	}
}

Обратите внимание, как мы передаем экземпляр из основного класса в конструктор MyPluginCommandExecutor. Это позволяет легко добраться до основных методов плагина.

Используя эту возможность, мы можем лучше организовывать свой код - если основной метод OnCommand() у вас стал большим и сложным, вы можете разделить его на под методы которые не загромождают основной класс плагина. Обратите внимание, что если ваш плагин имеет несколько команд, то вам нужно создавать исполнителя для каждой команды отдельно.  

Конфигурация/Настройки плагина  

TODOIcon Needs Updating!
This page may contain outdated information or needs more work, and needs to be updated. You might experience problems if you use the information you find here. In the meantime, you can always try asking on IRC, or perhaps the JavaDocs have the answer.
TODOIcon


Часто бывает так, что вашему плагину требуется переменная для сохранения, когда сервер выключен или выключается, как правило, какие-то настройки или имущество. Это достигается при помощи конфигурации, для этого Bukkit предоставляет свою встроенную функцию.   

Получаем конфигурацию для плагина

Bukkit automatically creates a Configuration object which is associated with your plugin. In order to work with it you will need to import the Configuration class and retrieve a reference to the object by calling the getConfiguration() method in your main plugin class, as shown below:  

package com.test.testplugin;

import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.util.config.Configuration;

public class TestPlugin extends JavaPlugin {
	protected FileConfiguration config;

	public void onEnable() {
		config = getConfig();
	}

	public void onDisable() {

	}
}

Here the variable config is the object which you will work with to set, get, save, and load settings and properties related to your plugin.

Настройка переменных конфигурации  

Now that we have our Configuration object, we can begin to save our properties and settings to it. Bukkit Configuration objects can handle many different types of variables, such as ints, booleans, and Strings (as well of lists of all of these). In order to set a property, you will need to use the following code:

public void onEnable() {
	this.getConfig().set("your boolean property", true);
	this.getConfig().set("your string property", "yes");
	this.getConfig().set("your int property", 22);
}

This code will create a config.yml which looks like this:

your boolean property: true
your string property: 'yes'
your int property: 22

You will notice that there is only one method which is used to set a property. The kind of property that will be saved is determined by the actual object you pass to the setProperty() method, so make sure it is of a type that Configuration objects can handle.

Bukkit Configurations also provide support for categories. In order to create categories for properties, simply put a decimal point as a seperator between the category and the property itself. An example use of this could be a situation where there is a different category for each player, where variables are set to different values for each different player. For example, you could use the following code to set the value of a few variables under the category of a particular player:

public void onEnable() {
	this.getConfig().set("player.damaged", true);
	this.getConfig().set("player.name", "LOL!");
	this.getConfig().set("player.damage", 22);
}

This will create a config.yml for your plugin that will look like this:

player:
    damaged: true
    name: LOL!
    damage: 22

Получение переменных конфигурации  

Получение переменных конфигурации достигается за счет использования различных методов получения, как показано здесь:

public void onEnable() {
	this.getConfig().set("your boolean property", true);
	this.getConfig().set("your string property", "yes");
	this.getConfig().set("your int property", 22);
	
	boolean bProp = this.getConfig().getBoolean("your boolean property", false);
	String sProp = this.getConfig().getString("your string property", "no");
	int iProp = this.getConfig().getInt("your int property", 0);
}

The first argument passed is the particular property that is being looked for, while the second argument is the default value to return if that property is not found in the configuration.

To get a property from a category, simply prepend the category name to the property you wish to retrieve and seperate the two with a decimal point, as such:

public void onEnable() {
	this.getConfig().set("player.damaged", true);
	this.getConfig().set("player.name", "LOL!");
	this.getConfig().set("player.damage", 22);

	boolean isDamaged = this.getConfig().getBoolean("player.damaged", false);
	String playerName = this.getConfig().getString("player.name", "no");
	int damage = this.getConfig().getInt("player.damage", 0);
}

Сохранение и загрузка с диска

Есть только две команды, которые вы должны знать, чтобы сохранять и загружать настройки с диска:

getConfig(); // получение конфигурации, если она не была загружена, загружается с жесткого диска
reloadConfig();; // перезагрузка конфигурации на диске 
saveConfig(); // сохранение конфигурации на диск

Usually, you would load the configuration on the plugin enable, and save at least once on plugin disable if anything was worth saving.

It is important to remember to call the save() method somewhat more frequently, in order to make sure that any properties that have been set are not forgotten on the termination of the server. You might think you only need to call this in onDisable(), but remember, if the server crashes before your plugin can properly close, any settings that haven't been saved will be lost. By default, configuration files will be saved in the file plugins/YourPlugin/config.yml, but you can use the Configuration class to read/write any file. Example:

File confFile = new File(plugin.getDataFolder(), "anotherfile.yml");
FileConfiguration conf = YamlConfiguration.loadConfiguration(configFIle);
conf.setProperty("player.name", "Herobrine");
// etc.
conf.save(confFile);

That will create a new file called plugins/YourPluginName/anotherfile.yml. You should avoid creating/modifying any files outside your own plugin's data folder (which you can get via the getDataFolder() call above) unless you have a very good reason.

 Разрешения (Permissions)  

With the new Bukkit API for permissions, they couldn't be easier. To find out if a player has a particular permission use the following:  

if(player.hasPermission("some.pointless.permission")) {
   //Do something
}else{
   //Do something else
}

You can also find if a permission has been set or not (equivalent to Java's null) with the following function:

boolean isPermissionSet(String name)

You may be wondering why there aren't any groups. The answer to that is because they aren't really needed. Previously one of the main uses for groups was to format chat messages. That however can be done just as easily with permissions. Inside your chat plugin's config you would define associations between permissions and prefixes. For example the permission "someChat.prefix.admin" would correspond to the prefix [Admin]. Whenever a player speaks with that permission their name will be prefixed with [Admin].

Another common usage might be to send a message to all users within a group. Again however this can be done with permissions with the following:

for(Player player: getServer().getOnlinePlayers()) {

    if(player.hasPermission("send.me.message")) {
        player.sendMessage("You were sent a message");
    }

}

Finally you may be asking, well how do I set and organise player's permissions if there are no groups? Although the bukkit API doesn't provide groups itself, you must install a permission provider plugin such as permissionsBukkit to manage the groups for you. This API provides the interface, not the implementation.

Настройка разрешений  

If you want more control over your permissions, for example default values or children then you should consider adding them to your plugin.yml. This is completely optional, however it is advised. Below is an example permissions config that would be appended to the end of your existing plugin.yml:

permissions:
    doorman.*:
        description: Gives access to all doorman commands
        children:
            doorman.kick: true
            doorman.ban: true
            doorman.knock: true
            doorman.denied: false
    doorman.kick:
        description: Allows you to kick a user
        default: op
    doorman.ban:
        description: Allows you to ban a user
        default: op
    doorman.knock:
        description: Knocks on the door!
        default: true
    doorman.denied:
        description: Prevents this user from entering the door

Firstly, each permission your plugin uses is defined as a child node of the permissions node. Each permission can then optionally have a description, a default value, and children.

Defaults

By default when a permission isn't defined for a player hasPermission will return false. Inside your plugin.yml you can change this by setting the default node to be one of four values:

  • true - The permission will be true by default.
  • false - The permission will by false by default.
  • op - If the player is an op then this will be true.
  • not op - If the player is not an op then this will be true.

Children

Before now you will probably be used to the * permission to automatically assign all sub permissions. This has changed with the bukkit API and you can now define the child permissions. This allows for a lot more flexibility. Below is an example of how you do this:

permissions:
    doorman.*:
        description: Gives access to all doorman commands
        children:
            doorman.kick: true
            doorman.ban: true
            doorman.knock: true
            doorman.denied: false

Here the doorman.* permission has several child permissions assigned to it. The way child permissions work is when doorman.* is set to true, the child permissions are set to their values defined in the plugin.yml. If however doorman.* was set to false then all child permissions would be inverted.

Создание собственных разрешений  

Если вы хотите знать о разработке собственных плагинов разрешений (те, которые могут установить права доступа. Проверьте учебник по созданию плагинов разрешений 

Scheduling Tasks and Background Tasks

Currently, Minecraft servers operate nearly all of the game logic in one thread, so each individual task that happens in the game needs to be kept very short. A complicated piece of code in your plugin has the potential to cause huge delays and lag spikes to the game logic, if not handled properly.

Luckily, Bukkit has support for scheduling code in your plugin. You can submit a Runnable task to occur once in the future, or on a recurring basis, or you can spin off a whole new independent thread that can perform lengthy tasks in parallel with the game logic.

There is a separate Scheduler Programming tutorial which introduces the Scheduler, and gives more information on using it to schedule synchronous tasks, and on kicking off asynchronous tasks in Bukkit.

Операции над блоками

Самый простой способ для создания или измения блоков. Для начала мы изменим блок находящийся над игроком (вверху) в 5ом блоке от позиции игрока. Для этого мы будем использовать событие PlayerMove (оно срабатывает каждый раз когда позиция игрока изменяется).

        

public void onPlayerMove(PlayerMoveEvent evt) {
    	Location loc = evt.getPlayer().getLocation();
    	World w = loc.getWorld();
    	loc.setY(loc.getY() + 5);
    	Block b = w.getBlockAt(loc);
    	b.setTypeId(1);
    }


Давайте разберем код. В начале мы берем позицию игрока, затем получаем "мир", который нам потребуеться для последующих операций над блоками. Далее мы берем текущую позицию игрока по высоте и увеличиваем её на 5ть. Затем мы получаем информацию о текущем блоке через команду w.getBlockAt(loc); В конце мы меняем ID блока на 1 (камень). Также мы можем изменить и его дополнительные свойства, вы можете добавить новую строку b.setData((byte)3); сразу после строки b.setTypeId(1); Как видите дополнительные свойства должны быть указанны числом с типом byte (8 bit).

Также мы рассмотрим довольно простой алгоритм для конструирования.

public void generateCube(Location point, int length){  // public visible method generateCube() with 2 parameters point and location
	World world = point.getWorld();

	int x_start = point.getBlockX();     // Set the startpoints to the coordinates of the given location
	int y_start = point.getBlockY();     // I use getBlockX() instead of getX() because it gives you a int value and so you dont have
                                                to cast it with (int)point.getX()
	int z_start = point.getBlockZ();

	int x_lenght = x_start + length;    // now i set the lenghts for each dimension... should be clear.
	int y_lenght = y_start + length;
	int z_lenght = z_start + length;

	for(int x_operate = x_start; x_operate <= x_lenght; x_operate++){ 
		// Loop 1 for the X-Dimension "for x_operate (which is set to x_start) 
		//do whats inside the loop while x_operate is 
		//<= x_length and after each loop increase 
		//x_operate by 1 (x_operate++ is the same as x_operate=x_operate+1;)
		for(int y_operate = y_start; y_operate <= y_lenght; y_operate++){// Loop 2 for the Y-Dimension
			for(int z_operate = z_start; z_operate <= z_lenght; z_operate++){// Loop 3 for the Z-Dimension

				Block blockToChange = world.getBlockAt(x_operate,y_operate,z_operate); // get the block with the current coordinates
				blockToChange.setTypeId(34);    // set the block to Type 34
			}
		}
	}
}


Этот код построит 3д куб или кубоид с необходимым размером (его необходимо вызвать принудительно в удобном для вас месте). Если же вам необходимо очистить блоки, то используйте значение ID равным 0 (он же блок воздуха)

Управляем инвентарем

Inventory manipulation might seem a little hard at first, but it's really easy once you get the hang of it. This section mostly covers player inventory manipulation, but the same applies to chest inventory manipulation as well if you find out how to get a chest's inventory :P. Here is a simple example of inventory manipulation:

public void onPlayerJoin(PlayerJoinEvent event) {
    Player player = event.getPlayer(); // Игрок, вошедший на сервер
    PlayerInventory inventory = player.getInventory(); // Инвентарь игрока "player"
    ItemStack diamondstack = new ItemStack(Material.DIAMOND, 64); // Стак алмазов
        
    if (inventory.contains(diamondstack)) { // А-ля условие на владение алмазами, если в инвенторе есть стак алмазов, то...
        inventory.addItem(diamondstack); // + 64 алмаза в инвентарь игроку "player"
        player.sendMessage(ChatColor.GOLD + "Welcome! You seem to be reeeally rich, so we gave you some more diamonds!");
        // оповещение игрока о добавлении в инвентарь 64 алмазов (текст золотого цвета).
    }
}

So inside onPlayerJoin we first make a few variables to make our job easier: player, inventory and diamondstack. Inventory is the player's inventory and diamondstack is a ItemStack that has 64 diamonds. After that we check if the player's inventory contains a stack of diamonds. If the player has a stack of diamonds, we give him/her another stack with inventory.addItem(diamondstack) and send a golden message. So inventory manipulation isn't actually that hard, if we wanted we could remove the stack of diamonds by simply replacing inventory.addItem(diamondstack) with inventory.remove(diamondstack) and change the message a little bit. Hopefully this helped! inventory.remove(diamondstack) - это тоже учти.

HashMaps and How to Use Them

When making a plugin you will get to a point where just using single variables to state an event has happened or a condition has been met will be insufficient, due to more than one player performing that action/event.

This was the problem I had with one of my old plugins, Zones, now improved and re-named to Regions. I was getting most of these errors because I didn't consider how the plugin would behave on an actual server with more than one on at any given time. I was using a single boolean variable to check whether players were in the region or not and obviously this wouldn't work as the values for each individual player need to be separate. So if one player was in a region and one was out the variable would constantly be changing which could/would/did cause numerous errors.

A hashmap is an excellent way of doing this. A hashmap is a way of mapping/assigning a value to a key. You could setup the hashmap so that the key is a player and the value could be anything you want, however the useful things with hashmaps is that one key can only contain one value and there can be no duplicate keys. So say for example I put "adam" as the key and assigned a value of "a" to it. That would work as intended, but then say afterwards I wanted to assign the value of "b" to key "adam" I would be able to and would get no errors but the value of "a" assigned to key "adam" in the hashmap would be overwritten because Hashmaps cannot contain duplicate values.

Defining a HashMap

public Map<Key, DataType> HashMapName = new HashMap<Key, Datatype>(); //Example syntax

//Example Declaration

public Map<Player, Boolean> pluginEnabled = new HashMap<Player, Boolean>();
public Map<Player, Boolean> isGodMode = new HashMap<Player, Boolean>();

Keep that code in mind because we will be using it for the rest of the tutorial on HashMaps. So, for example lets create a simple function which will toggle whether the plugin has been enabled or not. Firstly, inside your on command function which I explained earlier you will need to create a function to send the player name to the function and adjust the players state accordingly.

So inside on command you'll need this, the function name can be different but for the sake of simplicity it's best if you keep it the same.

Player player = (Player) sender;
togglePluginState(player);

This code above will cast the value of sender to player and pass that arguement to the function togglePluginState(). But now we need to create our togglePluginState() function.

public void togglePluginState(Player player){
    
    if(pluginEnabled.containsKey(player)){
        if(pluginEnabled.get(player)){
            pluginEnabled.put(player, false);
            player.sendMessage("Plugin disabled");
        } else {
            pluginEnabled.put(player, true);
            player.sendMessage("Plugin enabled");
        }
    } else {
        pluginEnabled.put(player, true); //If you want plugin enabled by default change this value to false.
        player.sendMessage("Plugin enabled");
    }

}

Now, what this code is doing is checking if the HashMap first contains the key player, so if it has been put into the hashap, if it is then we check the value of the HashMap key by get(player); if this is true then set value to false and send the player a message, else if the value is false then do the opposite, set the value to true and send a message again. But if the HashMap does not contain the key player then we can assume that this is their first run/use so we change the default value and add the player to the hashmap.

More Ideas for HashMaps

A HashMap (or really any kind of Map in Java) is an association. It allows quick and efficient lookup of some sort of value, given a unique key. Anywhere this happens in your code, a Map may be your solution.

Here are a few other ideas which are ideally suited to using Maps. As you will see, it doesn't have to be data that you store per player, but can be any kind of data that needs to be "translated" from one form to another.

Data Value Lookups

public Map<String, Integer> wool_colors = new HashMap<String, Integer>();

// Run this on plugin startup (ideally reading from a file instead of copied out row by row):
wool_colors("orange", 1);
wool_colors("magenta", 2);
wool_colors("light blue", 3);
   ...
wool_colors("black", 15);

// Run this in response to user commands - turn "green" into 13
int datavalue = 0;
if (wool_colors.containsKey(argument))
    datavalue = wool_colors.get(argument);
else {
    try { datavalue = Integer.parseInt(argument); }
    catch (Exception e) { ; }
}

Saving/Loading a HashMap

Once you know how to work with HashMaps, you probably want to know how to save and load the HashMap data. Saving and loading HashMap data is appropriate if

  • you don't want an administrator to edit the data manually
  • you need to save data in binary format (too complex to organize for YAML)
  • you want to avoid parsing block names and/or other objects from freeform text

This is very simple way how to save any HashMap. You can replace HashMap<Player,Boolean> with any type of HashMap you want. Let's continue using the "pluginEnabled" HashMap defined from the previous tutorial. This code saves the given HashMap to the file with given path.

public void save(HashMap<Player,Boolean> pluginEnabled, String path)
{
	try{
		ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(path));
		oos.writeObject(pluginEnabled);
		oos.flush();
		oos.close();
		//Handle I/O exceptions
	}catch(Exception e){
		e.printStackTrace();
	}
}

You can see it's really easy. Loading works very very similar but we use ObjectInputStream instead of ObjectOutputStream ,FileInputStream instead of FileOutputStream,readObject() instead of writeObject() and we return the HashMap.

public HashMap<Player,Boolean> load(String path) {
	try{
		ObjectInputStream ois = new ObjectInputStream(new FileInputStream(path));
		Object result = ois.readObject();
		//you can feel free to cast result to HashMap<Player,Boolean> if you know there's that HashMap in the file
		return (HashMap<Player,Boolean>)result;
	}catch(Exception e){
		e.printStackTrace();
	}
}

You can use this "API" for saving/loading HashMaps, ArrayLists, Blocks, Players... and all Objects you know ;) . Please credit me (Tomsik68) if you use this in your plugin.

/** SLAPI = Saving/Loading API
 * API for Saving and Loading Objects.
 * @author Tomsik68
 */
public class SLAPI
{
	public static void save(Object obj,String path) throws Exception
	{
		ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(path));
		oos.writeObject(obj);
		oos.flush();
		oos.close();
	}
	public static Object load(String path) throws Exception
	{
		ObjectInputStream ois = new ObjectInputStream(new FileInputStream(path));
		Object result = ois.readObject();
		ois.close();
		return result;
	}
}

Example implementation of this API: I'm skipping some part of code in this source

public class Example extends JavaPlugin {
	private ArrayList<Object> list = new ArrayList<Object>();
	public void onEnable()
	{
		list = (ArrayList<Object>)SLAPI.load("example.bin");
	}
	public void onDisable()
	{
		SLAPI.save(list,"example.bin");
	}
}

A minor note about this SLAPI and Java's ObjectOutputStream class. This will work un-modified if you are saving almost all well-known Java types like Integer, String, HashMap. This will work un-modified for some Bukkit types as well. If you're writing your own data object classes, and you may want to save their state using this technique, you should read up on Java's Serializable interface. It's easy to add to your code, and it will make your data persistent with very little work on your part. No more parsing!

Базы Данных

База данных представляет собой структурированную совокупность данных. Эти данные могут быть любыми - от простого списка игроков до перечня экспонатов картинной галереи. Для записи, выборки и обработки данных, хранящихся в компьютерной базе данных, необходима система управления базой данных. Поскольку компьютеры замечательно справляются с обработкой больших объемов данных, управление базами данных играет центральную роль в вычислениях. Реализовано такое управление может быть по-разному - как в виде отдельных утилит, так и в виде кода, входящего в состав других приложений.

Alta189 и PatPeter написали удобную библиотеку под названием SQLibrary. Данная библиотека позволяет упростить работу с БД. Так же для работы с БД вам понадобиться освоить синтаксис SQL.

SQLite

SQLite – это встраиваемая библиотека в которой реализовано многое из стандарта SQL. Её притязанием на известность является как собственно сам движок базы, так и её интерфейс (точнее его движок) в пределах одной библиотеки, а также возможность хранить все данные в одном файле. Я отношу позицию функциональности SQLite где-то между MySQL и PostgreSQL. Однако, на практике, SQLite не редко оказывается в 2-3 раза (и даже больше) быстрее. Такое возможно благодаря высокоупорядоченной внутренней архитектуре и устранению необходимости в соединениях типа «сервер-клиент» и «клиент-сервер».

MySQL

Другая популярная база данных SQL двигатель называется MySQL. Это ближе к серверу-класса, чем SQLite, где многие известные компании или веб-сайтов зависят от него миллионы веб-страницы хитов каждый день. При том, что безопасность приходит немного крутой кривой обучения, потому что MySQL имеет больше настраиваемых параметров и возможностей.

Получение скомпилированного плагина

После того как плагин написан, время задать вопрос: как получить рабочий jar-файл, который можно устанавливать на сервер, из набора файлов-исходников? В первую очередь установить сервер CraftBukkit на Вашем компьютере. Что бы сделать это ознакомьте с инструкцией Setting up a server (Настройка сервера). Затем Вам нужно экспортировать плагин в файл .jar, чтобы в дальнейшем запустить его на Вашем новом сервере. Чтобы сделать это в Eclipse, Выберите пункт меню File > Export. В появившемся окне под строкой "Java", выберите "JAR file", и затем выберите "next". Появится окно:

Экспорт в Eclipse

Проверьте что для экспорта выбрана Ваша директория с исходниками (в левой части окна). Справа, два файла с именем начинающимся на точку, не должны экспортироваться - они не нужны для работы плагина (снимите с них "галочки"). Очень важно, чтобы plugin.yml был выбран для экспорта; без него плагин не будет работать. Экспортируйте Ваш jar-файл, указав нужный путь.

Полученный jar-файл должен быть работоспособным плагином!nbsp;Естественно, если не были допущены ошибки в коде или в файле plugin.yml. Теперь можно скопировать плагин в директорию "plugins" Вашего сервера, перезагрузить или перезапустить сервер и приступить к тестированию! In order to connect to a server running locally on your computer, simply put "localhost" as the IP address of the server in Minecraft multiplayer. If you run into errors that you can't solve for yourself, try visiting the plugin development forum, asking in the bukkitdev IRC channel, or re-reading this wiki. Once you have a useful working plugin, consider submitting your project to dev.bukkit for consumption by the Bukkit community.

Советы и трюки

Поджигание Игрока

API Bukkit позволяет делать очень много интересных и нестандартных вещей. Вот несколько примеров:

Как поджечь кого-то всего лишь командой:

public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args){
    if(cmd.getName().equalsIgnoreCase("ignite")){
        Player s = (Player)sender;
        Player target = s.getWorld().getPlayer(args[0]); // target - игрок, чьё имя указано в команде в качестве параметр
        // Например, если команда была такова: "/ignite notch", то этим игроком будет "notch". 
        // Обратите внимание: Первый аргумент начинается с [0], а не [1]. Соответственно arg[0] возвращает заданное имя игрока. 
        target.setFireTicks(10000);
        return true;
    }
    return false;
}


Теперь, если написать команду типа /ignite Notch и если игрок "Notch" онлайн, Notch загорится!

Убиваем игрока

Продолжая тему, представляем способ убить игрока. Используем метод OnCommand для этого:  

public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args){
    if(cmd.getName().equalsIgnoreCase("KillPlayer")){
        Player player = (Player)sender;
        Player target = player.getWorld().getPlayer(args[0]);
        target.setHealth(0); 
    }
    return false;
}

Очередной способ убийства игрока, но уже со взрывом:

float explosionPower = 4F; // Настройка мощности взрыва
Player target = sender.getWorld().getPlayer(args[0]);
target.getWorld().createExplosion(target.getLocation(), explosionPower);
target.setHealth(0);

Request Section

Как создать плагин с использованием Maven

Using git, clone the BukkitPluginArchetype repo and build the archetype:

git clone git://github.com/keyz182/BukkitPluginArchetype.git
cd BukkitPluginArchetype
mvn clean install

Now, in the folder you want to create the plugin in, run the following commands:

mvn archetype:generate -DarchetypeCatalog=local

then select the following from the list when prompted:

uk.co.dbyz:bukkitplugin (bukkitplugin)

For groupid, enter what you'd use as the first part of the Java Package.For Artifactid, enter the last part of the package. Accept Version and package as is, then type Y <enter>

E.G.:

Define value for property 'groupId': : uk.co.dbyz.mc
Define value for property 'artifactId': : plugin
Define value for property 'version': 1.0-SNAPSHOT: 
Define value for property 'package': uk.co.dbyz.mc:

You'll now have a folder named as whatever you used for archetypeid. In that folder is a folder, src, and a file, pom.xml.

Open the <archetypeid>CommandExecuter.java file in src/main/java/<package>, and add the following code where it says //Do Something

Player player = (Player) sender;
player.setHealth(1000);

Now, go back to the base folder and run

mvn package

It may take a while downloading things, but let it do it's thing. When done, there'll be a folder called target, and a file called <archetypeid>-1.0-SNAPSHOT.jar inside it. Copy this file to the bukkit server plugin folder and reload the server.

Now, if you type the command /<archetypeid in minecraft while logged into the server, it'll give you full health!


 Добавляйте ещё примеры с HashMap пожалуйста

   

Примеры файлов и шаблоны

My Open Source Plugins

  • TameGrass - What you can learn from this plugin: Creating, deleting and checking blocks in a world. Loops and HashMaps, Permissions integration, Number formatting and Exceptions and more...
  • Zombies(Unfinished) - What you can learn from this plugin: HashMaps, Manipulating blocks, Random number generation, Entity spawning, ArrayLists and more...

If you have any more questions on this matter, don't hesitate to contact Adamki11s or anyone on the BukkitDev IRC channel

Language   EnglishбеларускаяDeutschespañolsuomifrançaisitaliano한국어Nederlandsnorskpolskiportuguêsрусскийlietuviųčeština
Advertisement