14. Python in Minecraft
Note
The Minecraft Python library is made by David Whale and Martin O’Hanlon. I highly recommend their book Adventures in Minecraft which contains a great deal more programs.
14.1. Setup
You will need to own Minecraft Java Edition (not Bedrock edition).
If you already have a Mojang or Microsoft account, go to the Minecraft website and click login. If you haven’t accessed it for years you may need to reset your password. If you already own Minecraft it will then tell you. If you don’t have an account, create one, and buy Minecraft Java Edition.
14.1.1. Setup Java
You will need to download and install Java from adoptopenjdk.net.
I recommend the latest (currently OpenJDK 16) because it will be useful for other things, but if you have problems you can fall back to using OpenJDK 8. Choose HotSpot and click the button to download.
14.1.2. Setup Server
Download the Adventures In Minecraft Starter Kit from
https://adventuresinminecraft.github.io and unpack it in a folder on your desktop. There are videos on the site that explain how to set it up.
Use Notepad or SublimeText to edit the file Server/server.properties. Change this setting
level-type=flat
to generate a flat world. (But it’s up to you what sort of world you prefer!)
To run the server, double click the StartServer file. It will open a server console window, and ask you press space.
If you want to generate another world later you can change
level-name=world2
and then run the server again.
Once the server is running, to stop nighttime from happening I suggest you type this at the server console
gamerule doDaylightCycle false
time set day
If only we could do that in real life!
You must leave the server console window open at all times. When you want to quit, first type
stop
at the server console, so it saves your world.
Advanced Challenge
Setup a more modern Minecraft server, such as PaperMC.
Then try to get the Raspberryjuice plugin to work with it so you can use it with Python. This is not easy; I couldn’t do it!
14.1.3. Setup Minecraft
Run the Minecraft launcher you downloaded from minecraft.net. We will not be using the default which is the latest version of Minecraft. Instead we will be using version 1.12.
Run the Minecraft Launcher. Click Installations then New Installation, then select version release 1.12. Then click Create. Then click Play next to the new installation in the list.
Minecraft will run. Click multiplayer. Then add server. Enter the server address as
localhost
Click ‘done’. Click on your server to connect to it.
14.1.4. Setup Mu
Mu is the Python editor we have already been using, so you probably already have it installed. However you need to make sure you have the latest version. You can download it from the links at the top of https://codewith.mu/en/download.
Run Mu. Click Mode and select Python3. Then click the small gadget icon in the bottom right hand corner of the window. Click third party packages. Type
mcpi
into the box. Click OK. The library will download.
If you are not using Mu you can install mcpi from the command line like this:
pip3 install mcpi
14.1.5. Summary
You need to have the Minecraft server, Minecraft (the client) and Mu all running at the same time. It may be useful to arrange them in separate windows. Your Python program will talk to the server, and Minecraft will also talk to the server, allowing you to see the results of your program in Mincraft.
14.2. Hello Minecraft
This program tests you have a connection to the Minecraft server and displays a message on the client.
1from mcpi.minecraft import *
2mc = Minecraft.create()
3mc.postToChat("Hello Minecraft World")
14.3. Coordinates
This program gets the player’s co-ordinates and prints them to the chat.
1from mcpi.minecraft import *
2import time
3
4mc = Minecraft.create()
5
6while True: # loop will make sure your game runs forever
7 time.sleep(1)
8 pos = mc.player.getTilePos()
9 print(pos)
10 mc.postToChat(pos)
14.4. Changing the player’s position
Find the coordinates of a location in your world, either by pressing F3 in the game, or running Program 14.2 Enter these coordinates in this program and run it to teleport to that location.
1from mcpi.minecraft import *
2
3mc = Minecraft.create()
4
5# change these to where you want to go
6x = 10
7y = 11
8z = 12
9
10mc.player.setTilePos(x, y, z)
14.5. Build a teleporter
Before you run this program, build two tiles in the game to be your teleporters and write down their co-ordinates.
1from mcpi.minecraft import *
2
3mc = Minecraft.create()
4
5# CHANGE THESE NUMBERS TO THE CO-ORDS OF YOUR TELEPORTERS
6
7teleporter_x = 742
8teleporter_z = 955
9
10destination_x = 735
11destination_z = 956
12
13while True:
14 # Get player position
15 pos = mc.player.getTilePos()
16 print(pos)
17
18 # Check whether your player is standing on the teleport
19 if pos.x == teleporter_x and pos.z == teleporter_z:
20 mc.postToChat("teleport!")
21 pos.x = destination_x
22 pos.z = destination_z
23 mc.player.setTilePos(pos)
Exercise
Add this line to the end of the program:
time.sleep(5)
Then add another line that teleports the player somewhere else.
14.6. Teleport player into the air
1from mcpi.minecraft import *
2
3mc = Minecraft.create()
4
5# CHANGE THESE NUMBERS TO THE CO-ORDS OF YOUR TELEPORTERS
6
7teleporter_x = 9
8teleporter_z = 12
9
10height = 30
11
12while True:
13 pos = mc.player.getTilePos()
14
15 # Check whether your player is standing on the teleport
16 if pos.x == teleporter_x and pos.z == teleporter_z:
17 mc.postToChat("teleport!")
18 pos.y += height # up in the air!
19 pos.x += 1 # move off the teleporter tile
20 mc.player.setTilePos(pos)
14.7. Teleport jump
This program does a series of teleports in quick succession to give the effect of a jump.
1from mcpi.minecraft import *
2import time
3
4mc = Minecraft.create()
5
6# CHANGE THESE NUMBERS TO THE CO-ORDS OF YOUR TELEPORTERS
7
8teleporter_x = 9
9teleporter_z = 12
10
11height = 20
12
13while True:
14 pos = mc.player.getTilePos()
15
16 if pos.x == teleporter_x and pos.z == teleporter_z:
17 mc.postToChat("teleport!")
18 # move off the teleporter tile so we dont land on it again
19 pos.x += 1
20 for i in range(0, height):
21 pos.y += 1 # move up a bit
22 time.sleep(0.1) # short delay of 0.2 seconds
23 mc.player.setTilePos(pos)
Exercise
Change the height of the jump.
Exercise
Make the jump faster.
Exercise
Move the player in X and Z directions as well as Y during the jump.
Advanced
Instead of checking if player is on a single teleporter tile, check if player is within a larger area. Use <, and, > operators.
14.8. Create a block
This program creates a block. Each type of block has it’s own number,
but if we import mcpi.block
we can use names instead remembering
numbers.
1from mcpi.minecraft import *
2from mcpi.block import *
3
4mc = Minecraft.create()
5pos = mc.player.getTilePos()
6x = pos.x
7y = pos.y
8z = pos.z
9blocktype = 1
10mc.setBlock(x, y, z, blocktype)
Exercise
Make the block appear a short distance from the player.
14.9. Types of block
AIR |
BED |
BEDROCK |
BEDROCK_INVISIBLE |
BOOKSHELF |
BRICK_BLOCK |
CACTUS |
CHEST |
CLAY |
COAL_ORE |
COBBLESTONE |
COBWEB |
CRAFTING_TABLE |
DIAMOND_BLOCK |
DIAMOND_ORE |
DIRT |
DOOR_IRON |
DOOR_WOOD |
FARMLAND |
FENCE |
FENCE_GATE |
FIRE |
FLOWER_CYAN |
FLOWER_YELLOW |
FURNACE_ACTIVE |
FURNACE_INACTIVE |
GLASS |
GLASS_PANE |
GLOWSTONE_BLOCK |
GOLD_BLOCK |
GOLD_ORE |
GRASS |
GRASS_TALL |
GRAVEL |
ICE |
IRON_BLOCK |
IRON_ORE |
LADDER |
|
LAPIS_LAZULI_ORE |
LAVA |
LAVA_FLOWING |
LAVA_STATIONARY |
LEAVES |
MELON |
MOSS_STONE |
MUSHROOM_BROWN |
MUSHROOM_RED |
OBSIDIAN |
REDSTONE_ORE |
SAND |
SANDSTONE |
SAPLING |
SNOW |
SNOW_BLOCK |
STAIRS_COBBLESTONE |
|
STAIRS_WOOD |
STONE |
STONE_BRICK |
STONE_SLAB |
STONE_SLAB_DOUBLE |
SUGAR_CANE |
TNT |
TORCH |
WATER |
WATER_FLOWING |
WATER_STATIONARY |
WOOD |
WOOD_PLANKS |
LAPIS_LAZULI_BLOCK |
WOOL |
14.10. Create a block inside a loop
This program creates a block over and over again in a loop. Move around to see it.
1from mcpi.minecraft import *
2from mcpi.block import *
3
4mc = Minecraft.create()
5
6while True:
7 pos = mc.player.getTilePos()
8 x = pos.x
9 y = pos.y
10 z = pos.z
11 blocktype = WOOL
12 mc.setBlock(x, y, z, blocktype)
Exercise
Make the block appear one meter below the player’s position.
Exercise
Change the block to something else, e.g. ICE
14.11. Create a tower of blocks
We will use a for
loop to easily build a tower of blocks.
1from mcpi.minecraft import *
2
3mc = Minecraft.create()
4pos = mc.player.getTilePos()
5x = pos.x + 3
6y = pos.y
7z = pos.z
8
9for i in range(10):
10 mc.setBlock(x, y + i, z, 1)
Exercise
How high can you make the tower?
Exercise
Change the program to create three towers next to one another.
14.12. Clear space
The setBlocks()
function lets us create a large cube of blocks. If
we create blocks of type AIR
this has the effect of removing all
blocks! This is such a useful thing that we will need it in the future,
therefore in this program we put it in its own function. Make sure to save the
program as clear_space.py
so you can import
it into the next
program.
1from mcpi.minecraft import *
2from mcpi.block import *
3
4def clear_space(mc, size):
5 pos = mc.player.getTilePos()
6 mc.setBlocks(pos.x-size, pos.y, pos.z-size, pos.x+size, pos.y+size, pos.z+size,
7 AIR)
8
9mc = Minecraft.create()
10
11clear_space(mc, 10)
14.13. Build a house
Make sure you have saved the previous Program 14.10 to the same directory before you run
this program because we are going to import
the function from
clear_space.py
. Save this program as house.py
.
1from mcpi.minecraft import *
2from mcpi.block import *
3
4# This MUST be the name you gave to your clear space program!
5from clear_space import *
6
7def make_house(mc, x, y, z, width, height, length):
8 mc.setBlocks(x, y, z, x + width, y + height, z + length, STONE)
9
10 # What happens if we make AIR inside the cube?
11 mc.setBlocks(x + 1, y + 1, z + 1,
12 x + width - 2, y + height - 2, z + length - 2, AIR)
13
14mc = Minecraft.create()
15pos = mc.player.getPos()
16x = pos.x
17y = pos.y
18z = pos.z
19
20width = 10
21height = 50
22length = 60
23
24# Use the function from the other program
25clear_space(mc, 10)
26make_house(mc, x, y, z, width, height, length)
Exercise
Run the program and manually bash a hole in the wall to see what is inside and to give you a way to get into the building.
Exercise
Change the program so it automatically makes a hole for a door.
Exercise
Lower the floor in your house.
Exercise
Add some furniture, torches, windows.
Advanced
Make the windows get bigger if you increase the size of the house.
Exercise
Try filling a house with LAVA, or WATER, or TNT (Be careful with TNT, too much will crash your computer!)
14.14. Build a street of houses
Make sure you have saved the previous Program 14.11
to the same directory before you run
this program because we are going to import
the function from
house.py
.
1from mcpi.minecraft import *
2from mcpi.block import *
3
4# This MUST be the name you gave to your clear space program!
5from clear_space import *
6# This MUST be the name you gave to your house program!
7from house import *
8
9mc = Minecraft.create()
10pos = mc.player.getTilePos()
11
12x = pos.x
13y = pos.y
14z = pos.z
15
16width = 10
17height = 5
18length = 6
19
20clear_space(mc, 100)
21
22for i in range(1, 100, 20):
23 print(x+i, y, z)
24 make_house(mc, x+i, y, z, width, height, length)
Exercise
How many houses are there? Make the street longer with more houses.
Exercise
Make the houses get taller as the street goes on.
Exercise
Add some towers to the street.
Advanced
Put a loop inside the loop to create multiple streets.
Advanced
Make some roads or fences.
Exercise
Make your houses out of TNT. Use flint tool on them.
14.15. Chat commands
This program can read chat messages posted by players. It builds a block next to any player who says “build”. This is the first example that will work for more than one player.
1from mcpi.minecraft import *
2
3mc = Minecraft.create()
4
5while True:
6 events = mc.events.pollChatPosts()
7 for event in events:
8 print(event)
9 if event.message == "build":
10 id = event.entityId
11 pos = mc.entity.getTilePos(id)
12 x = pos.x
13 y = pos.y
14 z = pos.z
15 mc.setBlock(x, y, z, 1)
16 mc.postToChat("done building!")
Advanced
Build a house around the player if the player says “house”.
Advanced
Build a lava trap if the player says “trap”.
Advanced
use mc.getPlayerEntityId(“fred”) to get the id of a certain player named Fred (or whatever your friend’s player name is). Build something at the position of this player.
14.16. Turtle
This requires the minecraftstuff package to work. You can install it
in Mu by clicking in the bottom right gadget and adding
minecraftstuff
to list of third party packages
In olden days at school we used robotic turtles to draw on paper. You may have done similar on the screen in Python or Scratch. This is the same but in Minecraft.
1from mcpi.minecraft import *
2from mcpi.block import *
3
4from minecraftstuff import MinecraftTurtle
5
6mc = Minecraft.create()
7pos = mc.player.getTilePos()
8pos.y += 1
9
10turtle = MinecraftTurtle(mc, pos)
11
12turtle.forward(5)
13turtle.right(90)
14turtle.forward(5)
15turtle.right(90)
16turtle.forward(5)
17turtle.right(90)
18turtle.forward(5)
Exercise
Draw a triangle, hexagon, etc.
Exercise
What do turtle.up(90) and turtle.down(90) do?