invalid argument

Minecraft Building from Script

We are running an intro to programming event in a few weeks and wanted to demo some building stuff with Minecraft on the raspberry pi without having to hard code buildings into the source code. This is a super quick and dirty script we can run to parse a text file, line by line and do run several commands:

  • create a single block of material at a given location using setBlock
  • create a multi block of material at a given location using setBlocks
  • move the player to a suitable vantage point

Each line of the file starts with the command word, followed by some optional parameters and the script just works through each command in realtime in minecraft.

I came up with some other desirable features - for authoring lines starting with a hash (#) are comments - for debugging and demonstration I added a message command, to output to the chat window, and a wait to space out the building work so that the pi cpu doesn’t get too hot.

Here’s the script:


import time
import mcpi.minecraft as minecraft

world = minecraft.Minecraft.create()

with open("build.txt") as file:
    for line in file:
        chunks = line.split()
        
        if chunks:
            command = chunks[0]
            
            if command.startswith('#'):
                print('Comment -> ' + line)
            elif command == 'message':
                startindex = len('message')
                #print(line[startindex:])
                world.postToChat(line[startindex:])
            elif command == 'goto':
                x = int(chunks[1])
                z = int(chunks[2])
                y = world.getHeight(x, z)
                #print('moving to ' + x + ' ' + z)
                world.player.setTilePos(x, y, z)
                
            elif command == 'block':
                material = int(chunks[1])
                x = int(chunks[2])
                y = int(chunks[3])
                z = int(chunks[4])
                world.setBlock(x, y, z, material)
            elif command == 'blocks':
                material = int(chunks[1])
                x1 = int(chunks[2])
                y1 = int(chunks[3])
                z1 = int(chunks[4])
                x2 = int(chunks[5])
                y2 = int(chunks[6])
                z2 = int(chunks[7])
                # print('multiple block from ' + x1 + ' ' + y1 + ' ' + z1 + ' to ' + x2 + ' ' + y2 + ' ' + z2)
                world.setBlocks(x1, y1, z1, x2, y2, z2, material)
            elif command == 'wait':
                delay = int(chunks[1])
                time.sleep(delay)
            
        
        

and an example script to flatten the ground, lay down some earth and grass prior to building:


goto 0 0 

# Clear some space by filling area with 'air'
blocks 0 -20 -20 -20 20 20 20 
wait 10

# layer of dirt
blocks 3 -20 -1 -20 20 0 20
wait 10

# layer of grass
blocks 2 -20 1 -20 20 1 20
wait 10

message done