скрипт на minecraft like minecraft
Скрипт на minecraft like minecraft
I created ScriptCraft to make it easier for younger programmers to create their own Minecraft Mods. Mods are written using the JavaScript programming language. Once the ScriptCraft mod is installed, you can add your own new Mods by adding JavaScript (.js) files in a directory.
This is a simple mod in a file called greet.js in the scriptcraft/plugins directory:
At the in-game prompt, type:
Anything you can do using the Spigot or CanaryMod APIs in Java, you can do using ScriptCraft in JavaScript.
ScriptCraft is a plugin for Minecraft Servers which lets operators, administrators and plug-in authors customize the game using JavaScript. ScriptCraft makes it easier to create your own mods. Mods can be written in Javscript and can use the full SpigotMC API or CanaryMod API. ScriptCraft works with all of the following Minecraft Server software:
I recommend using SpigotMC because both CanaryMod and CraftBukkit are no longer being actively developed. The ScriptCraft mod also lets you enter javascript commands at the in-game prompt. To bring up the in-game prompt press the / key then type js followed by any javascript statement. For example: /js 1 + 1 will print 2.
ScriptCraft also includes many objects and functions to make building and modding easier using JavaScript. The JavaScript Drone object bundled with ScriptCraft provides an easy way to build at-scale in Minecraft. See the attached temple.js file for an example of how you can use the sample Drone plugin to create new buildings in Minecraft.
Before installing ScriptCraft you must first install SpigotMC which is a special version of Minecraft Server that makes it easy to customize the game.
Installing and Running SpigotMC
Follow these steps to download and install SpigotMC.
Follow these steps to download and install ScriptCraft.
Once installed, a new scriptcraft/plugins directory is automatically created. All files in the scriptcraft/plugins directory will be automatically loaded when the server starts. Only players who are ops can use this plugin. You can grant a player op privileges by typing ‘op ‘ (replacing with your own Minecraft user name) at the server console prompt or by adding the player’s username to the ops.txt file in your server directory.
… This will create a black monolith structure 4 blocks wide by 9 blocks high by 1 block long. Take a look at the src/main/javascript/drone/drone.js file to see what ScriptCraft’s drone can do.
If you’re interested in customizing minecraft beyond just creating new buildings, take a look at the homes mod for an example of how to create a more fully-featured JavaScript plugin for Minecraft.
Listed below is a simple mod that will make blocks ‘Howl’ when they’re broken.
If you’re using CanaryMod instead of SpigotMC you can download the equivalent code.
To get started writing your own mod, take a look at some of the examples.
Because the SpigotMC API is open, all of the SpigotMC API is accessible via javascript once the ScriptCraft plugin is loaded. There are a couple of useful Java objects exposed via javascript in the ScriptCraft plugin:
__plugin – the ScriptCraft Plugin itself. This is a useful starting point for accessing other SpigotMC objects. The __plugin object is of type org.bukkit.plugin.Plugin and all of its properties and methods are accessible. For example: js __plugin.name returns the plugin’s name (JavaScript is more concise than the equivalent Java code: __plugin.getName() ).
server – The top-level org.bukkit.Server object. See the SpigotMC API docs for reference.
self – The player/command-block or server console operator who invoked the /js command. Again, this is a good jumping off point for diving into the SpigotMC API.
If you would like to contribute source code and/or documentation changes please read contributing.md
(You can ignore this if using CanaryMod)
ScriptCraft works with Bukkit Plugin and uses the Bukkit Configuration API. On first loading, ScriptCraft will create a config.yml file in the plugins/scriptcraft/ directory. This file looks like this:
You can find more information about ScriptCraft on my blog.
Developer Chris Cacciatore has created some interesting tools using ScriptCraft:
To launch a container with SpigotMC and ScriptCraft you can just do
You can find all files used to build this container in github project: docker-scriptcraft
Скрипт на minecraft like minecraft
Minecraft Script Documentation
Visit the official Website for information, guides and videos: https://mcscript.stevertus.com
The Compiler gets offered as Node.js/ Package that is installed locally on your machine. It enables much more features than the online version
For example: compile all files in a directory, direct output in new files, watch your files on changes, etc.
1.1 Installation of Node.js
The installation requires the Node.js environment and the Node Package Manager.
This is achieved the best way by using the installer: nodejs.org/en/download/
Just run it and install.
1.2 Installation of Minecraft Script
Now open your PCs console. (search CMD).
There you have to type in this command:
If a successful answer apears you have done everything right and can start.
Creates a new datapack for you with all basic files in a scripts folder. Takes as argument the datapack id!
2.2 mcscript compile
This will automatically compile your code if you make any changes (save). So you do not have to enter the above command with every change.
2.4 mcscript add [url or package]
This command adds a custom datapack to your directory. As argument an url to the resource or a mcScript Extension name can be used.
Get a list of all supported packages by running just mcscript add
2.5 Dev: mcscript modals
!!This command is intended only for developers who want to install their modals in the compiler.
A file must be specified and then the modals out of this file are written to a configuration file.
The generated files have always the same name as their root.
Instead of the name, you can enter a whole path where the new file should be:
You can also specify several files:
Also very well combinable with for-loops:
Variables (#vars), [constants] (#consts), and [Modals] (#modals) are stored separately for each file. Now you can create a global file with the extension ‘. gl. mcscript ‘. The compiler automatically detects globals and uses the declared objects in other files as well. For example, you can write the modals to a separate file.
Minecraft Script Syntax
Unlike mcfunction, each command is injected with a «/» or «run:».
Comments are announced with «//», if comments should also appear in the new file with «#»
Blank lines and skipping lines are ignored.
If a blank line is desired in the mcfunction, express this with a ‘#’ without a comment.
Two blank lines are reached with «##».
A comment across multiple lines can be expressed with:
4.1 Command Grouping / Wrapping
«as, at, positioned,align,in,dimension,rotated,anchored» can be grouped together:
The Argument / Arguments in the brackets have to be a string! (with ‘ ‘ or » «) It is also possible to use asat() for this:
«Groups can be listed like so:
run say command // also with if as(@p), at(@s), positioned(‘
‘), if(entity @s[tag=mytag]) < /say command >==> /execute as @p at @s positioned
if entity @s[tag=mytag] run say command «>
run optional a path should be given as string a name consisting of only characters, can be given without «»
Like every other programming language there are variables. They are initialized as follows: var test The variable can take in a value:
This value can be changed as often as you like.
Values can be assigned also only to special Minecraft selector like so. Also possible with playernames and placeholders:
Every value is saved in an independent scoreboard with it´s name or selector. So they are accessible with normal methods:
Variables can be merged together:
** Save command response to variable: **
The result of the command is written to the variable res. Example with /data get : ‘ var varResult = run: data get entity @s Pos[0] ‘
4.4 Boolean Variables (Tags)
bool [name] [selector](optional) = true|false
Boolean values can be declared like this. bool isCool = true => tag [global] add isCool The variable can be changed later: isCool = false => tag [global] remove isCool
Another type of variable is the constant, declared as following: const test = [value] This type cannot be changed!
Replace constants The value of an constant can still be changed when used. To do this, add ‘.repl()’ to the constant:
In our example, we want to replace a :
Maps are essentially key-value pairs kind of like a dictionary. We define it with the Map-operator:
In the brackets you can define as many pairs as you like:
It then can be accessed with
Arrays are pretty similar to Maps, but use a list of values instead of pairs:
The values can be accessed by the index of the item starting with 0.
4.6 If/Else Statements
If functions are similar to grouping:
With some additional features:
In front of every argument a «!» can be inserted to reverse the meaning:
After the end an «else» can be attached:
4.7 Logical operators
In combination with grouping and if-else statements logical operators can be used:
Switches makes the case distinction much easier. It´s able to test easily and clearly certain variables. e.g:
Here test is checked for more than 10, if that does not apply to less than 10 and finally outputed as default. Also abbreviable:
One of the most helpful features is the for loop. It takes in neutral numbers.
From first Argument to second Argument is optional outputed as third Argument
var_name is out of the box defined as «i», but can be changed with the third argument:
That makes especially with two-dimensional loops sence:
Raycasting is a big thing in Minecraft 1.13 and provides unlimeted opportunities. But it is a bit difficult, so why not making it easier? With Minecraft Script this is really really easy now:
This alone sets everywhere where you look a stone Particles and block limits are also pretty easy:
Now there are beautiful effects and a max range of 10 blocks. The second argument sets the porous blocks.
So the ray only goes through air. You can also negate the porous blocks and set with a «!» the not porous blocks:
The ray goes through all blocks, but white wool.
As third optional argument a target can be set:
Now Mcscript knows that the target is a block and executes the command only if the block is white wool.
Now Mcscript knows that the target is an entity and executes as the entity if it´s hitted. So the armor stand would say test.
The while loop is defined like so:
The grouped commands are executed as long as the condition [cond] is true.
If the condition to start is not true, the grouping will not be executed!
As a condition, all operators and arguments of the If conditions can be used. e.g.
For while-loops you can also use stop and continue:
The do-while loop works in a similar way to the while loop, with the small difference that the code block is executed and then the condition is checked. So the loop is executed at least one time.
The forEach Loop is a loop found in almost any programming language. It is similar to Minecraft Script’s for-loop, but it works dynamically (it does not run on generate, but in Minecraft)
The Command is executed 10 times and the current value is saved each in the scoreboard i. Der Command wird also 10mal ausgeführt und der aktuelle Wert jeweils in dem scoreboard i gespeichert. You can also access the value like so. e.g. Faculty:
Modals are like functions or methods. That means you can define them:
A modal is always introduced with the keyword followed by the name and the arguments in the brackets.
If you use the modal like that, the values are used and it outputs everything.
You are also able to use multiple arguments.
There are optional and predefined arguments, too:
Using Maps and Arrays You can also use the Map and Array type of constants in modals:
Override Modals Modals that have already been created can be overridden within the process:
Arguments and actions are exchanged completely and used for the ongoing process.
Replace arguments The value of an argument can still be changed when used. To do this, add ‘.repl()’ to the argument:
In our example, we want to replace an entered test:
4.15 JavaScript Modals
JavaScript Modals are modals, you can write in JavaScript. You can define them like other modals:
For multi line output I recommend doing something like this:
A JavaScript modal is always introduced with the keyword followed by the name and the arguments in the brackets.
The arguments are accessible inside with their names.
You are also able to use multiple arguments.
There are optional and predefined arguments, too:
Tips and tricks
Use console.log() to output some information to the console while compiling without effecting the return value.
There are already some helpful predefined modals. Please read the specific documentation here.
You have ideas which modals should be a standart? Send me your configuration file to check.
4.17 Error handling and Debugging
If you find errors that make no sense in the context, please notify the team.
Debug keyword You can debug your code with the keyword «Debug» and find some errors in Minecraft Script much easier. You can place these anywhere in your code and they have no affect on the compiled output.
IDEs and Syntax Highlighting
GitHubs Atom Editor: mcscript (credit: Trojaner)
Now there´s nothing left than: Happy Developing
Thanks to all who use Minecraft Script and read this documentation. Contact me if you have a proposal, problem or error.
About
A programming language for Minecraft Vanilla
Делаем свой minecraft на JavaScript
Добро пожаловать в самую запутанную архитектуру проекта. Да я умею писать вступление.
Попробуем сделать небольшую демку minecraft в браузере. Пригодятся знания JS и three.js.
Немного условностей. Я не претендую на звание лучшее приложение столетия. Это всего лишь моя реализация для данной задачи. Также есть видео версия для тех кому лень читать(там тот же смысл, но другими словами).
В конце статьи есть все нужные ссылки. Постараюсь как можно меньше воды в тексте. Объяснять работу каждой строки не буду. Вот теперь можно начать.
Для начала чтобы понимать какой будет итог, то вот демка игры.
Разделим статью на несколько частей:
Структура проекта
Вот так выглядит структура проекта.
index.html — Расположение канваса, немного интерфейса и подключение стилей, скриптов.
style.css — Стили только для внешнего вида. Самое важное это кастомный курсор для игры который располагается в центре экрана.
texture — Здесь лежат текстуры для курсора и блока земли для игры.
core.js — Основной скрипт где происходит инициализация проекта.
perlin.js — Это библиотека для шума Перлина.
PointerLockControls.js — Камера от three.js.
controls.js — Управление камерой и игроком.
generationMap.js — Генерация мира.
three.module.js — Сам three.js в виде модуля.
settings.js — Настройки проекта.
Игровой цикл
В core.js нужно провести инициализацию three.js, настроить его и добавить все нужные модули от игры + обработчики событий… ну и игровой цикл запустить. В учет того, что все настройки стандартные, то объяснять их нет смысла. Поговорить можно про map (он принимает сцену игры для добавления блоков) и contorls т.к. он принимает несколько параметров. Первый это камера от three.js, сцену для добавления блоков и карту чтобы можно было взаимодействовать с ней. update отвечает за обновление камеры, GameLoop — игровой цикл, render- стандарт от three.js для обновления кадра, событие resize также стандарт для работы с канвасом (это реализация адаптива).
Настройки
В настройки можно было вынести и другие параметры, например, настройки three.js, но я сделал без них и сейчас здесь лишь пара параметров отвечающие за размер блоков.
Генерация карты
В классе Map у нас есть несколько свойство которые отвечают за кеш материалов и параметры для шума Перлина. В методе generation мы загружаем текстуры, создаем геометрию и меш. noise.seed отвечает за стартовое зерно для генерации карты. Можно рандом заменить на статичное значение чтобы карты всегда была одинаковая. В цикле по X и Z координатам начинаем расставлять кубы. Y координата генерируется за счет библиотеки pretlin.js. В конечном итоге мы добавляем куб с нужными координатами на сцену через scene.add( cube );
Камера и управление
Я уже говорил, что controls принимает параметры в виде камеры, сцены и карты. Также в конструкторе мы добавляем массив keys для клавиш и movingSpeed для скорости. Для мыши у нас есть 3 метода. onClick определяет какая кнопка нажата, а onRightClick и onLeftClick уже отвечают за действия. Правый клик(удаление блока) происходит через raycast и поиска пересеченных элементов. Если их нет, то прекращаем работу, если есть, то удаляем первый элеент. Левый клик работает по схожей системе. Для начала создаем блок. Запускаем рейкаст и если есть блок который пересек луч, то получаем координаты этого блока. Далее определяем с какой стороны произошел клик. Меняем координаты для созданного куба в соответствии со стороной к которой мы добавляем блок. градация в 5 единиц т.к. это размер блока(да здесь можно было использовать свойство из settings).
Как работает управление камерой?! У нас есть три метода inputKeydown, inputKeyup и update. В inputKeydown мы добавляем кнопку в массив keys. inputKeyup отвечает за очистку кнопок из массива которые отжали. В update идет проверка keys и вызывается moveForward у камеры, параметры которые принимает метод это скорость.
Ссылки
Как и обещал. Весь материал который пригодится.
Если есть желание, то на можете добавить свой функционал к проекту на гитхаб.
Getting Started with Skript
Tutorial by: eyesniper2
Hello and welcome to Skript!
This is a general «How to Skript» guide that will hopefully give you everything you need to get setup and begin writing your first script! This tutorial includes parts originally written by Demon on the original DBO forums and LimeGlass. This tutorial will assume that you are familiar with making a Bukkit servers, but not with programing. So lets get into it!
What is Skript?
Skript is a plugin for Bukkit/Spigot, a popular Minecraft server mod, that allows server admins to easily modify how Minecraft works without programming anything.
— Peter «Njolbrim» Güttinger
Skript was created by Peter Güttinger, also know as Njolbrim or Njol, and first released on Feb 16, 2012. The goal of Skript is to provide a simple way for non-programmers to make their own mini plugins (called scripts). Skript is designed as an event driven language.
This is achieved with triggers, whereof each is a collection of conditions and effects. Each time a trigger is called all conditions are checked, and if all are met, the effects are executed.
— Peter «Njolbrim» Güttinger
This means for any of your code to be run, something in the game or your server must happen. This is call an event or a trigger. These can include things like commands, a passage of time, or the actions of a player (mining a block or jumping). After something has happened, then the series of conditions and effects is run through for things to actually happen based on that event. A condition is a yes or no question your code asks the server. This can include things like: is the player online, is the player holding a pickaxe. An effect is then something that happens, these can include giving the player an item or moving the player. These building blocks combined with other elements you will learn later can be combined to produce powerful features for your server very quickly. These features will be discussed in depth later in this tutorial.
There is also a Skript IDE called SkIDE which offers a lot of nice features such as autocomplete and code highlighting.
A very basic example of a Skript can be found below:
Please note that #s are used for comments and will not do something
The script above sends the message «Welcome to Skript» to everyone on the server every time someone joins the server. You might notice that the script is very easy to understand, this is because scripts are meant to be very readable, English and easy to understand.
Setting up Skript
After setting up your base server, download the correct version of Skript from one of the sources below
Minecraft 1.9.4 to 1.14.x: bensku’s fork, 2.4x versions: https://github.com/SkriptLang/Skript/releases
Minecraft 1.8.x
bensku’s fork, 2.2-dev36 (Recommended): https://github.com/SkriptLang/Skript/releases/tag/dev36
⚠ This version is for 1.9, but should work on 1.8 too, but is not supported.
Notes
How to make a Script?
Now lets make your first script file!
Congrats you have just written your first script! How lets talk about loading it on the server.
How to load a Script?
Scripts are not loaded when you save their sk files. Instead they are loaded on the server startup or when you use the /sk reload command:
Go on try it! Now when joining your server «Welcome to Skript!» will be broadcast to all users!
Any errors with your script will be either shown in the chat to the user who typed the reload command or the server console. Unlike plugins, with scripts you don’t need to restart your server to add or update features. It can all happen through the reload command. However be careful as this can also cause a small freeze on your server that your players might experience when loading large scripts.
Now that you can create and load scripts, lets get into the core concepts of Skript!
Core Concepts of Skript
Events
Events are called when something happens. So when a player clicks on something, takes damage, dies, when a mob does something, or even when the environment does something else completely independent of entity interaction. This will allow you to make something happen when something else happens. For example:
Note the spacing. Every time there is a colon ( : ), then next line down is indented one more. You can either use a tab or spaces as indentation. Length of the indentation doesn’t matter, but an event must use the same indentation on each line. I prefer to use the tab key because I only need to hit it once per indent. The actual code is pretty simple. When an explosion happens, it gets cancelled. This would be useful if you don’t want TNT, creepers, or even the Ender Dragon to destroy stuff on your server. Keep in mind that this cancels the actual explosion event, meaning that players will not get hurt either. So when an explosion happens, it stops it from happening. You can easily change the outcome to be whatever you want. Another example could be as dramatic as killing all players on the server.
Conditionals
Conditionals are an essential part of any script. They are pieces of code that check to see if a condition is met before executing the rest of the script/trigger.
Structure of conditionals is as follows:
else if s and else are optional.
You can add as many else if as you want.
An example with permissions is below:
This will create an explosion that is slightly smaller than TNT, but it will only do so if the player has the correct permission. Conditionals can also be used to check things like if the player has an item in his/her inventory, or what a line on a sign says. You can even use multiple conditionals so that an event has to meet all of them before moving on.
In this script the player must right click on a sign with the first line of «[Shop]», have the correct permission, and 2 gold nuggets. Then the effects occur. In this case the player will loose 2 gold nuggets and receive some bread.
Commands
You can create commands with ease in Skript. Check out this tutorial: https://skripthub.net/tutorials/10
We will use some commands in the next examples.
Loops
Loops can be used to complete repetitive tasks that would otherwise be much more complicated. For example if you wanted to see if there was a chest near you, you would need to check every block in a certain distance to see if it was a chest. This can be done easily using a loop:
Here we also set a default value for the command, just in case the player didn’t enter one. In the loop expression we see the number has been replaced with an «argument» This means that whatever number you typed in the command will be put here instead. If a number was not entered in this command, then 3 will be used because it was set to be the default value. If you would like to see exactly how far a radius value is, then you can use this script to make a sphere out of blocks so you can visibly see the size.
The /clear command is so that you can easily delete the sphere that you made. Also because you will be at the center of the sphere, you will need a way to teleport yourself out. These Commands may cause a small amount of damage to your server if used close to the ground. Please use them while flying to get the full effect.
The parts of code with the curly brackets < >are called variables. You will learn about them in the next section.
While Loops
While loops are loops that runs the code as long as a specified condition is positive:
Please note that while loops don’t have a delay, so they are faster than a tick and will crash the server if you are using Minecraft stuff (like blocks) without at least a tick delay: wait a tick
Example usage:
Variables
Variables are used to store information under a name. Think of it like a box with a label on it. When you want to get the info you put in that box, you just go look for the one with the right label on it. Skript does the same thing with Variables, which are the computers equivalent of a box. You save information like this:
The reason for this is so that we can get this information later. So maybe we want to check if a command was performed by this player before. We would do it like so:
Every time a variable is used in a script you must must put it in curly brackets < >to tell Skript that you are using a variable. Above is a very simple home script. We store the location of the player in a variable called
Now if a player tries to do /home they will get an error message and then the rest of the trigger will stop. If you forget to stop the trigger, then the rest of the events not indented under the if statement will continue as normal. Also if the if statement is false, then none of the code indented under it will be read and the player will not get an error message.
The main problem with our current script is that if one person sets their home location under the
At the end, it looks like this:
list variable with expressions in variable names
Now the player’s name who set their home is in the variable. For example when it checks if the variable is set, it will check
Lets make some admin commands for our home system, using some benefits of list variables:
<_count>(with a underscore prefix) makes the variable local to the event. Local variables can’t be accessed from other events, and will be deleted at end of the current event.
When looping a list variable, loop-value will be value and loop-index will be index of the currently looped variable. In this case the index is a player UUID, the value is a location.
Functions
Functions are an useful way to make reusable sections of code. If you have a bunch of code that is often repeated, instead of copying and pasting the code in many places you can just put it in a function then call the function when you need to run the code.
Addons
Addons are separate plugins written by other developers to add more functionality to Skript. Addons are a massive part of the Skript community and you will see them discussed everywhere. For example you can use databases, make Discord bots, send web requests, manage other plugins like Citizens and WorldGuard, play various particle effects and much more with the addons. To use an addon, all you have to do is add the addon to your server’s ‘plugins’ directory with any addition plugins they might need. Then you can use their syntax in your scripts after you restart the server.
Where to find documentation/resources
Depending on your version of Skript, Njol’s website or Bensku’s website will have all the up to date «vanilla» syntax. However, other websites such as Skript Hub host not just Skripts documentation, but all of the addons documentation in one place! This means you can search every expression, condition, effect or event in one place. Links for both can be found below:
For vanilla Skript:
For vanilla Skript and addons