Computercraft Turtle Replication Challenge

I'm throwing my hat in the ring for the Computercraft Competition to make a self-replicating turtle. It's a bit of late entry -- the deadline was Nov 1, 2012, and the forum has long closed. But I love computercraft, so who cares!

Computercraft is a mod for minecraft. In it you program Lua code to control little turtles.

 turtles can only interact with these three blocks
turtles can only interact with these three blocks

They can:

  • Move up, down, and forward. This costs 1 fuel.
  • Look up, down, and forward (1 block) -- they can't see their environment
  • Mine blocks up, down, and forward.
  • Place blocks up, down, and forward.
  • Turn left or right.
  • Look in and manage an inventory of 16 slots
  • Craft items, assuming their inventory is completely empty other than the craft.
  • Refuel, using any item that can be used as fuel in a smelter.
  • Take the FIRST item out of a chest, or dump items in a chest

So... they can mine and turn for free, but moving costs fuel. And the biggest problem is the list of things they can't do:

  • They don't know their position or location
  • They have no idea what's in any block around them, other than directly in front of them
  • They can't interact with a chest other than the very first slot

They have a few capabilities added since the 2012 post, which I'm taking full advantage of

  • They can move an item from one slot in a chest to another slot, and generally look at the list of items in a chest
  • They can detect what item is in their inventory, or what's in front of them. So they learn it's "oak_planks". Previously, all they could do was check whether it was the same as another item in their inventory! Much harder.

This brings us to the challenge, which is to use a computercraft turtle... to build two computercraft turtles. Possible in theory, but in practice I've only seen maybe 1 completion of the challenge. You're guaranteed that the turtle starts at the bottom of an oak tree. There are various additional requirements for the challenge, which I've basically ignored, but I did display the status for the human watcher.

Here's a video of it happening. There's no sound or audio commentary. Sorry!

I proceed in hardcoded phases:

  • Chop a single log, craft it into planks, and consume it for fuel, so the turtle can move.
  • Chop down the first tree. Place a block at the top, so only small oak trees grow (not large oaks, which are more complicated to chop down). Also craft a chest to store materials we gather.
  • Note: At this point I speed up tick speed and place an automatic bonemeal machine to grow the tree, so it's more fun to watch.
  • Continue to chop down trees until we build up enough planks and fuel for later phases. We also add a sign to the left, to update the player on where we're at (phase, fuel, material-gathering progress).
  • Determine the turtle's height by going to some known height and counting back to where we were. We could either go down to bedrock, or up to world height. Since bedrock is bumpy, I picked world height.
  • Dig at ideal gold ore height, gather gold. Along the way, we've gotten some cobblestone.
  • Dig just above bedrock, gathering diamonds and redstone
  • Dig sideways at sea level in a straight line, looking for sand. Note that I temporarily slow down tick speed, because if the turtle moves itself out of loaded chunks, it shuts off and forgets everything.
  • Craft and place a furnace. Smelt the gold and sand.
  • Craft: a glass pane, a computer, a pickaxe, a crafting table, a turtle, and finally a crafting-mining turtle, same as we started it.

Along the way, the turtle refuels when it gets low on fuel, and deposits items in the chest or drops them to clear space for crafting and more gathering.

How long does it take to make two copies? Well, in a deep sense it doesn't matter, because you can keep doubling indefinitely. But just for amusement, let's find out. I added some logging profiling code to find out what the slow steps are, and they tell us the answers.

  • I sped up the tick rate, but luckily the internal clock also gets adjusted the same way, so we can measure what would have been the clock time no problem: main (1 times): 6959 seconds
  • We also bonemealed the trees! So we better take that into account too: awaitTree (22 times): 175 seconds. Let's change that to a more average value. A minecraft tree takes an average of 16 minutes to grow (provided there's space and light -- we actually set it to perpetual noon, but since it would be easy to place a torch, I'll ignore that)

So the real time is 5.8 hours waiting for trees to grow, plus 1.9 hours for everything else -- a total of 7.75 hours.

If you kept re-placing the turtles, that means you'd have over 1 million turtles in a week. (Well, you wouldn't, because chunkloading--but that's something you could do with turtles too, in theory.)

Tagged ,
leave comment

Minecraft Villager Trading Halls: Probability Math

Recently I was making a villager trading hall in minecraft.

One of the main goals of a trading hall is to collect all villager trades. One of the trickiest is books, provided by a librarian. I got to wondering -- how long is this going to take?

Well, we can do some math to find out.

There are currently (as of Minecraft Java Edition 1.21.11) 40 trade-able books. 36 of them are available from the enchanting table, treasure chests[1], or trading.

4 are available only from treasure chests and trading. These are called Treasure enchantments.

  • Curse of Binding
  • Curse of Vanishing
  • Frost Walker I and II
  • Mending

There's also three books, which can be found only from treasure chests. We don't care about them for trading halls:

  • Soul Speed
  • Swift Sneak
  • Wind Burst

There are no books available only from enchanting and not trading.


The core mechanic of searching for book trades is resetting. If we look at a librarian and find it has a trade we don't want, we reset it.

Villagers remember their profession and trades forever after trading. But if we haven't traded with a villager, we simply remove its profession, and then give it a profession again. Then we can see if we like the new starting trades better.

This is very useful for librarians, because they have every book available as a starting trade, so there's no need to investigate later trades for books.

These are the options to make the villager forget their profession I'm aware of:

  • Ignore the villager and get a new one (for example with a breeder), moving or killing the old one. This isn't a "reset" per se, but it acts similarly.
  • Break the profession block manually. In the case of a librarian, the lectern. When breaking the block, the villager loses their profession instantly.
  • Block the path between the villager and their profession block. I haven't seen this documented, but they reset at the same time as trades reset (twice per minecraft day). I did this by dropping the villager 1 block using a piston.
  • Move the villager at least 48 taxicab blocks from their profession block. (Not tested)
  • Move the profession block with a piston. This is an instant reset, but you can't do it for a lectern in Java edition. (Not tested)

Some of these are instant, some take longer. Once villagers are shown a profession block, it only takes them a couple seconds to get their new profession, so that part is easy.

I found breaking and re-placing blocks to be annoying, so I settled on moving librarians up and down with pistons. It takes about 5 real-time minutes for them to reset, so I used about 50 librarians to counteract that. By the time I finished checking all 50 librarians, they were ready to reset again because 5 minutes had passed.

Then the question is: How many librarians do we need to look at, to get every book?


Well, the first question is: what are we interested in? Let's say we're interested in getting each of the 40 enchantments.

Well, it turns out each enchantment is equally likely: there's a 1/40 chance of getting it. Well actually, 1/60 -- there's a chance that no book trade is offered at all.

Then this is the coupon collector's problem, a classic math problem.

The number of trades to look at turns out to be: 3/2 x n x H(n) where H(n) is the n-th harmonic number. For n=40, H(40) = 1/1 + 1/2 + 1/3 + ... + 1/39 + 1/40 = 4.2785. So we need to check 257 librarians on average to get every enchantment.


But, are we really okay with that result? Given that Efficiency V is available as a starting trade, I want a librarian with Efficiency V, not Efficiency I!

There are:

Enchantment Level
Aqua Affinity I
Channeling I
Curse of Binding I
Curse of Vanishing I
Flame I
Infinity I
Mending I
Multishot I
Silk Touch I
Fire Aspect II
Frost Walker II
Knockback II
Punch II
Depth Strider III
Fortune III
Looting III
Loyalty III
Luck of the Sea III
Lunge III
Lure III
Quick Charge III
Respiration III
Riptide III
Sweeping Edge III
Thorns III
Unbreaking III
Blast Protection IV
Breach IV
Feather Falling IV
Fire Protection IV
Piercing IV
Projectile Protection IV
Protection IV
Bane of Arthropods V
Density V
Efficiency V
Impaling V
Power V
Sharpness V
Smite V
  • 9 tradable enchantments with a max level of I
  • 4 with a max level of II
  • 13 with a max level of III
  • 7 with a max level of IV
  • 7 with a max level of V

What's the chance of getting each level of enchantment? It's equal. So for Mending, there's a 1/60 chance to get Mending I, because it's the only choice. For Efficiency, there's a 2/3 * 1/40 x 1/5 = 1/200 chance to get Efficiency I, Efficiency II, or Efficiency V.

How do we calculate the coupon collector's problem for un-equal probabilities? Well... it's really complicated[2].

But the answer is that we will have to talk to an average of 933 librarians to get all enchants at max level.


But hey. We can buy Efficiency V for 17 emeralds, if we get the right trade. Are we really okay getting a 64 emerald trade? What if we want only the best trades?

Enchantment Level Cost
Aqua Affinity I 5-19
Bane of Arthropods V 17-71
Blast Protection IV 14-58
Breach IV 14-58
Channeling I 5-19
Curse of Binding I 10-38
Curse of Vanishing I 10-38
Depth Strider III 11-45
Density V 17-71
Efficiency V 17-71
Feather Falling IV 14-58
Fire Aspect II 8-32
Fire Protection IV 14-58
Flame I 5-19
Fortune III 11-45
Frost Walker II 16-64
Impaling V 17-71
Infinity I 5-19
Knockback II 8-32
Looting III 11-45
Loyalty III 11-45
Luck of the Sea III 11-45
Lunge III 11-45
Lure III 11-45
Mending I 10-38
Multishot I 5-19
Piercing IV 14-58
Power V 17-71
Projectile Protection IV 14-58
Protection IV 14-58
Punch II 8-32
Quick Charge III 11-45
Respiration III 11-45
Riptide III 11-45
Sharpness V 17-71
Silk Touch I 5-19
Smite V 17-71
Sweeping Edge III 11-45
Thorns III 11-45
Unbreaking III 11-45

Mostly, the price range is based only on the level, but there are a few minor complications:

  • Some price ranges go above 64! In the game, these get capped. For this reason, you're 8 times more likely to get Efficiency V for 64 emeralds than any other number.
  • Treasure enchantments (in bold above) are double the price of any other enchantment. This is actually a double -- they're never offered for odd numbers of emeralds. Interesting!

The chance of getting an Efficiency V book at the best possible price is: 1/16,500 = 2/3 x 1/40 x 1/5 x 1/55 (because there are 55 possible different prices -- counting ones above 64).

To get every book at the best price, we'd need to talk to 45,594 librarians[2] to get every max-level enchant at the best price.

[1]: I think [2]: Source code here. This uses the inclusion-exclusion principle to estimate set sizes, together with optimizations to take care of repeat probabilities.

Tagged ,
leave comment

Hack-a-Day, Day 27: Minecraft Mod

Today I made a minecraft mod, using Fabric. Modding sure has changed a lot since I last tried it in Forge, maybe ten years ago! Java's changed a little too, even.

My mod adds a dirt slab, that's it. I didn't really have time to get past the basics, but I think the occasional hack that's just a learning experience is okay.

Code and mod download are both on github this time.

Fabric is well-documented and friendly. The main downside is that there's no "abstraction later" between Minecraft and the mod. This means your mod will work with exactly one minecraft version on release. Additionally, when a new version of minecraft is released, you need to update and re-release your mod (and there are usually actual changes to be made).

Tutorials used:

Tagged ,
leave comment

Controlling a computercraft turtle remotely

Screen Shot 2015-10-18 at 7.16.59 PM
Screen Shot 2015-10-18 at 7.17.30 PM

  1. Install Redis: https://www.digitalocean.com/community/tutorials/how-to-install-and-use-redis
  2. Install Webdis
  3. Start a minecraft server with computercraft. You will need to have the http API enabled, which is the default.
  4. Put down a turtle I recommend a turtle with a crafting square and a pickaxe. I also recommend giving it a label. If you’re not trying the turtle replication challenge, either disable fuel or get a fair bit of starting fuel. Write down the computer’s id.
  5. Put down a chunk loader, if you’re in a modpack that has them, or DON’T log out. Computers and turtles can’t operate unless the chunks are loaded. If you’re putting down a chunkloader, I surrounded them with bedrock for foolproofing.
  6. Open the turtle and download the following script, changing “redis.example.com” to your own redis instance: pastebin get 8FjggG9w startup
    After you have the script saved as ‘startup’, run it or reboot the computer, and it should start listening for instructions.

    redis = "http://redis.example.com" 
    queue = "sshbot" .. os.getComputerID()
    return_queue = queue .. "_return"
    print("Remote webdis queues on icyego: " .. queue .. " and " .. return_queue)
    print("Receiving remote commands.")
    
    function exec(str)
      print("Running: " .. str)
      f = fs.open("tmp", "w")
      f.write(str)
      f.close()
      p = loadfile("tmp")
     status, err = pcall(function () p = loadfile("tmp"); return p() end)
      if status then
        status, ret = pcall(function() return textutils.serialize(err) end)
        if status then
          result = ret
        else
          result = ""
        end
      else
        result = "Error: " .. err
      end
      print(result)
      return result
    end
    
    print("Now receiving remote commands.")
    while true do
      handle = http.get(redis .. "/BRPOP/" .. queue .. "/5.txt")
      if (handle and handle.getResponseCode() == 200) then 
        str = handle.readAll()
        handle.close()
        str = string.sub(str, string.len(queue) + 1)
        result = exec(str)
        if string.find(result, "Error: ") then
          result2 = exec("return " .. str)
          if string.find(result2, "Error: ") then a=0 else result=result2 end
        end
        http.post(redis, "LPUSH/" .. return_queue .. "/" .. result)
      end
    end
    
  7. On your local machine, save the following, again replacing “redis.example.com”:

    #!/bin/bash
    function send() {
      curl -s -X POST -d "LPUSH/sshbot${1}/${2}" "http://redis.example.com" >/dev/null
    
    }
    
    function get() {
      curl -s -X GET "http://redis.example.com/BRPOP/sshbot${1}_return/20.json" | jq .BRPOP[1]
    }
    
    if [ $# -ne 1 ]; then
      echo "Usage: rlwrap ./sshbot <COMPUTER_ID>"
      exit 1
    fi
    ID=$1
    
    while read LINE; do
      send ${ID} "$LINE"
      get ${ID}
    done
    
  8. Run: rlwrap ./sshbot , where is the turtle’s ID. You should be able to send commands to the computer now.

Tagged , ,
leave comment

Running a forge server on headless linux

I’ve had a lot of trouble getting Minecraft Forge to run headless. They have a friendly installer option that I just can’t use in my situation, but one of the devs seems actively hostile around providing help to headless servers, so I didn’t bother asking forge for help. I thought I’d write up what I had to do to get things working. As a warning, it requires some local work; you can’t do everything headless with these directions.

I’m running Minecraft 1.6.4, with the latest version of forge for that, 9.11.1.965.

  1. Locally, download and start the minecraft client for the correct version at least once. Not sure if you’ll need to ‘play online’ or not. If you have the current installer, you need to make a new profile with the correct minecraft version and play that.
  2. Copy ~/.minecraft/libraries to the headless machine.
  3. Download forge (the installer version, not the universal) from http://files.minecraftforge.net/. The non-adly version is the little star for non-interactive use.
  4. Run

    java -jar forge-1.6.4-9.11.1.965-installer.jar --installServer
    
  5. Delete the installer, you don’t need it any more.

  6. Install any mods you want to the ‘mods’ directory, edit server.properties, etc. Normal server setup.
  7. To execute the server, run the file indicated in the installer. In my case, I run

    java -jar minecraftforge-universal-1.6.4-9.11.1.965-v164-pregradle.jar nogui
    

Alternatively, you can install the entire server locally and copy it over.

Tagged
leave comment