Using the Bukkit Scheduler In ScriptCraft

In this post we’ll use the Bukkit Scheduler to decrease the likelihood of our Minecraft client being dropped while performing computationally intensive tasks in our ScriptCraft code–tasks like building gigantic structures. As an added bonus we also get to watch our huge structures being built (rather than just poofing into existence as they currently do). Poof!

MCMap Live Shot For Perspective (the jagged tops are an artifact of the rendering software).

From what I can gather ScriptCraft currently performs all of its work in the main server thread. The main thread also takes care of a number of important tasks including the networking logic which manages the connection to your Minecraft client. Now, running on the main thread isn’t a problem in itself, it only becomes a problem once you start doing some heavy lifting like rendering a 500 x 100 x 500 rectangular prism (at least for my little server):

25,000,000 blocks (most clipped beyond the horizon)

If your ScriptCraft code is gobbling up too much time you’ll end up seeing this screen:

Dirty Screen

I see it frequently.

One way to decrease your chances of seeing the old dirt screen is to punt off your ScriptCraft tasks off into another thread thereby giving the main server thread a little breathing room. Here’s an example of using the schedule to draw a large rectangular prism:

As you can see it is only a few extra lines of code and doesn’t add too much complexity. We get a reference to the scheduler and call the scheduleAsyncDelayedTask method supplying a reference to the ScriptCraft plugin and the task we wish to run.

Now a async delayed task isn’t the only type we can use in our ScriptCraft–in fact sometimes we shouldn’t use it. All in all Bukkit allows us to schedule four different types of tasks:

1. Synchronous Delayed – Schedules a one-time task to run in the main thread with an optional delay.
2. Synchronous Repeating – Schedules a repeating task to run in the main thread on a specified period with an optional delay.
3. Asynchronous Delayed – Schedules a one-time task to run in a separate thread managed by the scheduler with an optional delay.
4. Asynchronous Repeating – Schedules a repeating task to run in a separate thread managed by the scheduler with an optional delay.

In our example above I scheduled an async delayed task and you can too as long as your task is thread safe and doesn’t utilize the Bukkit API (so far all I have done with just ScriptCraft and JavaScript has been fine). If you need to use the Bukkit API inside your task, then you will have to use a synchronous task or just run your ScriptCraft code like you always have. You can also find out more about the Bukkit Scheduler in the Doxygen docs.

Finally, remember this is no silver bullet! If your doing too much work and your server can’t keep up nothing will save you from being dropped.

ScriptCrafting A Quest In Minecraft

Below I will use the Bukkit API to implement a simple quest, including a quest-giving NPC, objective, and reward.

Spawn Quest Giving NPC

First we need to spawn the NPC who will offer the quest to players as well as give out the rewards. Creating an NPC with Bukkit looks like this:

The above will create a Villager NPC, which isn’t ideal because every time we right-click him he will show us his inventory, but it will work for this tutorial.

Track Quest Progress

So now that we have an NPC, we need to give it a memory so it can track each player’s respective quest progress. To save each player’s current quest progress we save the index of their state in a array where each key is the player’s ID (similar to what we did in the Wolfbot post).

Let’s also create a method which initializes another hash that maps quest state to a blurb of text we want the NPC to spit out when interacted with by a player:

As you can see from the code our quest involves a gang of skeletons who are running amok nearby. The quest is for the player to simply kill 10 and then return for their reward. Of course we are still missing the logic that will cause the Villager to spit out the text and drop the rewards if the quest objective is met:

Watch For Quest Completion

There are only two bits of code left to round out our quest logic. We need a command for the player to accept the quest and also a listener to watch for skeleton deaths–specifically deaths that were at the hands of our questing player:

The full code list can be found at the end of this post. Drop that code in your js-plugin directory and you can start questing:

1. /jsp spawn_npc
2. Right-click to move through the quest prompts.
3. /jsp accept
4. Go hunt down and slay 10 skeletons.
5. Return to the NPC and claim your XP reward!

Skeleton Menace

Next Steps

There are a number of improvements you can add to this ScriptCraft plugin; however, if you really want to put time into creating quests I would recommend checking out the Citizens plugin which is much more powerful and lets you script NPC interactions with YAML. There is also a helpful repository with script examples.

Here is our little quest plugin in its entirety:

Scripting A Simple Minecraft Bot

Here I will implement a simple in-game wolfbot with ScriptCraft in under a hundred lines of code. In the beginning our bot will only support a few commands–mostly serving as a glorified “donkey”. In later posts we will add more functionality. You can find the code for our bot in the wolfbot Github repo.

First off, my intent in this post is not to create the next best pet/bot plugin, especially since there are already some good pet plugins out there. The purpose of this post is for us to learn how to create a bot in ScriptCraft.

We will also be using the brand new ScriptCraft plugin feature which was included in the newest release. The plugin feature is a neat addition since it gives us data persistence and also the ability to safely package various features so that non-op players can indirectly use ScriptCraft goodies.

ScriptCraft Plugins

There are three main parts to a ScriptCraft plugin:

1. Definition
2. Storage
3. Initialization

Plugin Definition

The plugin’s definition section is where the meat of the plugin resides. Here we define various methods to implement the features we want to support in our plugin. We can also place helper methods here for accessing our plugin’s data storage.

Data Storage

ScriptCraft makes it absurdly easy to persist data with your plugins. To save data we need only add a key to our plugins store and assign it an object. Behind the scenes ScriptCraft will serialize the data into JSON when needed and save it for us to be accessed later.

Initialization

We can perform any initialization our plugin requires inside the ready method provided by ScriptCraft. Any code we place inside ready will run only after all other JavaScript functions have been loaded. In this section we can add hooks to Minecraft events and also determine what functionality we want to expose from the definition section using the command method.

A Simple Plugin

Below, check out each of the three sections in action in this plugin which can get and set a string:

If you would like to read more about ScriptCraft plugins, then I recommend reading Walter Higgins original post introducing them.

Wolfbot Specs & Demo

Before we get started coding our wolfbot, let’s look at the list of various actions I would like the bot to support:

1. summon – Summons the bot.
2. dismiss – Dismisses the bot.
3. come – Causes the bot to target you and follow.
4. stay – Causes the bot to sit and stay put.
5. pack – Causes the bot to show you its inventory and allow you to take and place items with it.

You can see these commands in action below:

Wolfbot Implementation

To implement the actions we described above we will create a method for each action in the plugin definition section.  Most everything inside these methods are Bukkit API calls.  You can see the definition section below.  Reference the Bukkit API docs to find out more about the API calls I make.

All there is left to do now is create our storage and associate plugin commands with our plugin’s functionality so that players who are not ops can also have bots. Checkout the code for the complete plugin in the Github repo.

Suggestions

Is there a topic you would like to see covered here?  I want to hear your input. Send me an email with any suggestions for future posts.  If you liked this post, then you might also like Visualizing Towers Of Hanoi In Minecraft.

Visualizing The Towers Of Hanoi In Minecraft

In this post I will talk about the Towers Of Hanoi puzzle and create a few neat in-game visualizations for various puzzle sizes using ScriptCraft.

Towers Of Hanoi

The Towers Of Hanoi is a math puzzle that involves usually three poles and disks. The puzzle starts with all the disks stacked on the left-most pole with the largest disk on the bottom and the smallest on top. For example, here is the initial configuration for a 3 disk puzzle….in the snow:

Initial Configuration With 3 Disks

The object of the puzzle is to move all the disks from the left-most pole to the right-most while following these three rules:

1. You can only move one disk at a time.
2. You can only move the very top disk from a pole.
3. You can only stack a smaller disk onto a bigger one.
Sketch It Out By Hand

Now that you have the initial configuration and the rules, grab a piece of scratch paper and see if you can sketch all the moves needed to complete a three disk puzzle. With three disks it will not take you long to draw them all out.  If you get stuck check out the Towers Of Hanoi Wikipedia page for help.

Tracking & Visualizing Moves

Now that you are probably tired of drawing out moves manually, lets devise a recursive algorithm to solve this puzzle for an any number of disks.  In fact, the Towers Of Hanoi is one of those fun and almost magical problems that if you characterize it the right way you can almost word for word translate it into a programming language.  To solve a puzzle with disks and three poles we have to:

1. Move all the disks but the bottom disk (n – 1 disks) from the left pole to the middle pole.
2. Move the bottom disk to the right-most pole.
3. Move all the disks from the middle pole (n – 1 disks) to the right-most pole.
Javascript Translation

Running the above with ScriptCraft will cause the moves to be printed out.  If you want to see how I rendered the move visualizations with colored wool checkout my Towers Of Hanoi Gist which you can drop into your ScriptCraft js-plugins directory and start creating move visualizations.

Comparing Puzzles Of Different Disk Size

Placing together visualizations from different disk-sized puzzles yields the most interesting results.  Here is a picture showing Towers Of Hanoi moves starting on the left with 3 disks and ending with the moves required to solve an 8 disk puzzle on the right:

Moves From Disks 3-8 Compared

As you can see the number of moves required to solve the puzzle for every additional disk grows by leaps and bounds!  Specifically for n disks the fewest moves required to solve a puzzle is $2^n - 1$ moves.

• So if you have a puzzle with 10 discs it would take $2^{10} - 1 = 1023$ moves.
• A puzzle with 30 disks would take $2^{30} - 1 = 1,073,741,823$ moves!
Suggestions

Is there a topic you would like to see covered here?  I want to hear your input. Send me an email with any suggestions for future posts.  If you liked this post, then you might also like Visualizing Sorting Algorithms In Minecraft.

Visualizing Sorting Algorithms In Minecraft

In this post I will use ScriptCraft to create static visualizations in Minecraft for a couple well-known sorting algorithms.

Sorting Algorithms

Sorting algorithms are a popular branch of algorithms. For young computer scientists sorting algorithms are the vehicle for learning important concepts in the field such as Big O notation and time-space tradeoffs. For older computer scientists, this family of algorithms are still interesting enough to devote time for research and analysis (e.g. Library Sort). And yet despite the ubiquity of these algorithms I doubt most of us have developed strong intuitions on how they work, or have simply forgotten–myself included.

Static Visualizations

A few years ago, Aldo Cortesi, a New Zealand coder, made a case for static over animated visualizations as the tool of choice for understanding the flow of sorting algorithms.  His argument is that these animated visualizations are initially unclear and take longer to understand. We have trouble with these animations because humans estimate distances in space well, but are generally poor at estimating distances in time, so why when trying to teach potentially confusing material would we play to our weakness? Static visualizations play to our strength.

Below there are three sorting algorithm visualizations along with a few notes. Look at each picture from right to left to follow the flow of each algorithm. If you hadn’t already guessed from the pictures we are sorting colored wool and using Minecraft’s internal IDs for each block. A list of all block IDs can be found at MinecraftInfo.

Bubblesort

Bubblesort Meets Colored Wool

A simple sorting algorithm. If your list is small and your data mostly sorted, then there is certainly nothing wrong with this little algorithm.

Notice:

• When a line of wool is swapped with another the most it moves is by one line.
• Towards the end of the rectangle (towards the left) there is a stretch where no wool is swapped and yet the algorithm is still “sorting”.
Shell Sort

Shell Sort Meets Colored Wool

Discovered by Donald Shell in ’59. Compare the picture above with that of Bubblesort and you should notice:

• Swaps between rows can move wool more than one line (unlike poor old Bubblesort)!
• The visualization has a shorter width than that of Bubblesort. This is due to the fact that Shell Sort took fewer passes sorting the same data.
Quicksort

Quicksort Meets Colored Wool

Discovered by Tony Hoare in ’60. Quicksort is popular because it is usually very fast in practice.

Notice:

• There is a pattern where first wool swaps are made from farther away, but then are followed by swaps with closer lines of wool. This is because Quicksort takes a bigger uglier problem (like sorting a lot of wool) and divides into smaller similar problems (sorting just a little bit of wool). The smaller problems are easier to solve and can be recombined to create a solution for the original big ugly problem.
• The orange wool does not appear at the very top like in the previous sorts.  (Don’t worry it’s there, but for some reason Minecraft doesn’t always show the blocks I render with ScriptCraft).
More Visualizations

After your done reading this post I sugget you visit Cortesi’s sortvis site to see more sorting algorithm visualizations. If you are interested in creating your own sorting algorithm visualizations in Minecraft you can find the JavaScript code I used as a Gist. You’ll need ScriptCraft installed which is a little painful, but once installed you can do plenty of other neat things like creating L-system fractals.

Suggestions

Is there a topic you would like to see covered here?  I want to hear your input. Send me an email with any suggestions for future posts.

L-systems In Minecraft

In this post I use ScriptCraft, Minecraft, and L-systems to create fun in-game fractals and discuss how you can too.

ScriptCraft

ScriptCraft is a Minecraft mod that allows you to run JavaScript inside the game using the Java Rhino library.  Walter Higgins the creator of Scriptcraft modeled the library’s API after the programming language Logo which is basically a Lisp with turtle graphics (more on that in a bit).  Lucky for us having turtle graphics makes working with L-systems super easy since a turtle interpreter is a natural way to render L-systems.

L-systems

L-systems were originally created by a Hungarian botanist named Aristid Lindenmayer who was interested in modeling plant growth.  You can model arboreal growth, brush and shrubs, and also roots (by changing the modeling environment a bit to bring about different tropisms). You can do more than model trees though–there are tons of interesting fractals to make like Koch curves, Dragon curves, and Sierpinksi’s Triangles.

Learning exactly how L-systems work requires a bit of knowledge about grammars–a topic which I slept through while in Computing Theory class.  I’ve picked up some knowledge since then, but to keep this post short I’ll avoid any grammar shenanigans and say an L-system is simply a series of commands that change over time due to a corresponding set of rules.  So if you change the starting commands and/or the set of rules you will get different types of structures like this romantic torch-lit fractal which my turtle built just for you baby (by following the commands).

Torch-lit Fractal

Putting It All Together

In order to start drawing L-systems in Minecraft, I installed ScriptCraft following the instructions on the ScriptCraft Github repo and then went searching for a JavaScript L-system library I could poach.  I settled on John Snyder’s L-system implementation which is BSD licensed and can be found on his blog.  He also has a turtle implementation which would be a good candidate for wrapping around the ScriptCraft Drone (ScriptCraft’s turtle).

Converting this L-system implementation to work in ScriptCraft was a breeze and you can see the code in the Github repo I created for this project.  Follow the installation instructions there if you want to start creating L-system fractals in Minecraft….like this one:

Petrified Tree

Oh and make you sure experiment with lava and water for cool 2D fractals turned 3D:

2D-3D Lava Fractal

Email me any cool fractals you make–especially if you have better texture packs and lighting mods installed than I.  Also if you liked this, check out my post on Visualizing Sorting  Algorithms.