If you want to know more about how to use the API, including tutorials, see my projects and download code, visit my minecraft page.
Structure
- minecraft.py
- Class Minecraft - main class for connecting and interacting with the game
- Class camera - changing camera angle and postion
- Class player - getting and changing the players position and setting
- Class entity - getting and changing entities position and setting
- Class events - retreiving events which have occured in the game
- block.py
- Class Block - definition of a block, specifically its type
- event.py
- Class BlockEvent - definition of a block event, specifically what event, what block and what player
- vec3.py
- Class Vec3 - generic class for managing a 3 dimension vector (i.e. x,y,z)
- connection.py - internal module used by the api
- util.py - internal module used by the api
Compatability
Not all functions and block types are available on all version of the api, by each function you will see a logo which shows whether that function is available:
Available on Minecraft: Pi edition
Available on RaspberryJuice
Minecraft
"Main class for interacting with the Minecraft world, includes functions for creating a connection, modifying players and blocks and capturing events".create(address = "localhost", port = 4711)
"Create connection to Minecraft (address, port) => Minecraft object"
#use default address and port
mc = minecraft.Minecraft.create()
#specify ip address and port
mc = minecraft.Minecraft.create("192.168.1.1", 4711)
.getBlock(x,y,z)
"Get block (x,y,z) => id:int"
blockType = mc.getBlock(0,0,0)
.getBlocks(x0,y0,z0,x1,y1,z1)
"Get a cuboid of blocks (x0,y0,z0,x1,y1,z1) => [id:int]"
.getBlockWithData(x,y,z)
.setBlocks(x0,y0,z0,x1,y1,z1,blockType, blockData)
"Set a cuboid of blocks (x0,y0,z0,x1,y1,z1,id,[data])"
#sets many blocks at a time, filling the gap between 2 sets of x, y, z co-ordinates
mc.setBlocks(-1, -1, -1, 1, 1, 1, block.STONE.id)
.getHeight(x,z)
"Get the height of the world (x,z) => int"
#find the y (vertical) of an x, z co-ordinate which represents the 'highest' (non-air) block
y = mc.getHeight(0,0)
.getPlayerEntityIds()
"Get the entity ids of the connected players => [id:int]"
#get the entity id's of the players connected to the game
entityIds = mc.getPlayerEntityIds()
for entityId in entityIds:
print entityId
.getPlayerEntityId(playerName)
"Get the entity id for a named player => [id:int]"
#get the entity id of a name player 'martinohanlon'
entityId = mc.getPlayerEntityId("martinohanlon")
print entityId
.saveCheckpoint()
"Save a checkpoint that can be used for restoring the world"
mc.saveCheckpoint()
.restoreCheckpoint()
"Restore the world state to the checkpoint"
mc.restoreCheckpoint()
#get the block id's in a cuboid
blocks = mc.getBlocks(-1,-1,-1,1,1,1)
for block in blocks:
print block
blocks = mc.getBlocks(-1,-1,-1,1,1,1)
for block in blocks:
print block
.getBlockWithData(x,y,z)
"Get block with data (x,y,z) => Block"
#retrieves a block object for the block at 0,0,0
blockObj = mc.getBlockWithData(0,0,0)
.setBlock(x,y,z)
blockObj = mc.getBlockWithData(0,0,0)
.setBlock(x,y,z)
"Set block (x,y,z,id,[data])"
#sets a block at an x, y, z co-ordinate to a particular type
mc.setBlock(0,0,0,block.DIRT.id)
#sets a block to a particular type and 'subtype'
mc.setblock(0,0,0,block.WOOD.id, 1)
mc.setBlock(0,0,0,block.DIRT.id)
#sets a block to a particular type and 'subtype'
mc.setblock(0,0,0,block.WOOD.id, 1)
.setBlocks(x0,y0,z0,x1,y1,z1,blockType, blockData)
"Set a cuboid of blocks (x0,y0,z0,x1,y1,z1,id,[data])"
mc.setBlocks(-1, -1, -1, 1, 1, 1, block.STONE.id)
.getHeight(x,z)
"Get the height of the world (x,z) => int"
y = mc.getHeight(0,0)
.getPlayerEntityIds()
"Get the entity ids of the connected players => [id:int]"
entityIds = mc.getPlayerEntityIds()
for entityId in entityIds:
print entityId
.getPlayerEntityId(playerName)
"Get the entity id for a named player => [id:int]"
entityId = mc.getPlayerEntityId("martinohanlon")
print entityId
.saveCheckpoint()
"Save a checkpoint that can be used for restoring the world"
.restoreCheckpoint()
"Restore the world state to the checkpoint"
.postToChat(message)
"Post a message to the game chat"
mc.postToChat("Hello Minecraft World")
.setting(setting, status)
"Set a world setting (setting, status). keys: world_immutable, nametags_visible"
#change world immutable to True
mc.setting("world_immutable", True)
#change nametags_visible setting to False
mc.setting("nametags_visible", False)
Minecraft.player
.getPos()"Gets the player's position in the world as a Vec3 of floats (decimal numbers), if the player is in the middle of a block x.5 is returned"
playerPos = mc.player.getPos()
.setPos(x,y,z)
"Moves the player to a position in the world by passing co-ordinates ([x,y,z])"
mc.player.setPos(0.0,0.0,0.0)
.getTilePos()
"Gets the position of the 'tile' the player is currently on."
playerTile = mc.player.getTilePos()
.setTilePos(x,y,z)
"Move the player to a tile position in the world by passing co-ordinates ([x,y,z])"
mc.player.setTilePos(0,0,0)
.setting(setting, status)
"Set a player setting (setting, status). keys: autojump"
#change the autojump setting to True
mc.player.setting("autojump", True)
.getRotation()
"Get the rotational angle (0 to 360) for the player => [angle:float]"
angle = mc.player.getRotation()
print angle
.getPitch()
"Get the pitch angle (-90 to 90) for the player => [pitch:float]"
pitch = mc.player.getPitch()
print pitch
.getDirection()
"Get unit vector of x,y,z for the player's direction => [Vec3]"
direction = mc.player.getDirection()
print direction
Minecraft.entity
The entity functions are used in conjunction with the .getPlayerEntityIds() function to interact with the entity (or players) in a game. Entity functions are useful for multiplayer games.
#get the entity id's of the players connected to the game
entityIds = mc.getPlayerEntityIds()
1stEntityId = entityIds[0]
2ndEntityId = entityIds[1]
...
entityIds = mc.getPlayerEntityIds()
1stEntityId = entityIds[0]
2ndEntityId = entityIds[1]
...
"Gets an entities position in the world as a Vec3 of floats (decimal numbers), if the entity is in the middle of a block x.5 is returned"
entityPos = mc.entity.getPos(entityId)
.setPos(entityId,x,y,z)
"Moves the entity to a position in the world by passing co-ordinates ([x,y,z])"
mc.entity.setPos(entityId,0.0,0.0,0.0)
.getTilePos(entityId)
"Gets the position of the 'tile' the entity is currently on."
entityTile = mc.entity.getTilePos(entityId)
.setTilePos(entityId, x,y,z)
"Move the entity to a tile position in the world by passing co-ordinates ([x,y,z])"
mc.entity.setTilePos(entityId,0,0,0)
.getRotation(entityId)
"Get the rotational angle (0 to 360) for an entity => [angle:float]"
angle = mc.entity.getRotation(entityId)
print angle
.getPitch(entityId)
"Get the pitch angle (-90 to 90) for an entity => [pitch:float]"
pitch = mc.entity.getPitch(entityId)
print pitch
.getDirection(entityId)
"Get unit vector of x,y,z for an entities direction => [Vec3]"
direction = mc.entity.getDirection(entityId)
print direction
Minecraft.camera
.setNormal(entityId)"Set camera mode to normal Minecraft view ([entityId])"
#set camera mode to normal for a specific player
mc.camera.setNormal(entityId)
.setFixed()
"Set camera mode to fixed view"
#set camera mode to fixed
mc.camera.setFixed()
.setFollow(entityId)
"Set camera mode to follow an entity ([entityId])"
#set camera mode to follow for a specific player
mc.camera.setFollow(entityId)
.setPos(x,y,z)
"Set camera entity position (x,y,z)"
#set camera position to a specific position of x, y, z
mc.camera.setPos(0,0,0)
Minecraft.events
.pollBlockHits()"Block Hits (Only triggered by sword) => [BlockEvent]"
#get block event hits that have occured since the last time the function was run
blockEvents = mc.events.pollBlockHits()
for blockEvent in blockEvents:
print blockEvent
for blockEvent in blockEvents:
print blockEvent
.pollChatPosts()
"Chat posts => [ChatEvent]"
#get chat post events (messages) since the last time the function was run
chatEvents = mc.events.pollChatPosts()
for chatEvent in chatEvents:
print chatEvents
for chatEvent in chatEvents:
print chatEvents
.clearAll()
"Clear all old events"
mc.events.clearAll()
Block
"The definition of a Block in Minecraft, used to describe a block type and (if applicable) its data; also contains constants for the blocks type id's, e.g. BLOCK.AIR.id"
#create block of a specific type
blockObj = block.Block(id)
#create a block of a specific type and apply a data value
blockObj = block.Block(id, data)
.id
"The id (or type) of block"
Data Values of blocks:
3: Pointing south
4: Pointing north
5: Facing up
STONE_BRICK:
0: Stone brick
1: Mossy stone brick
2: Cracked stone brick
3: Chiseled stone brick
STONE_SLAB / STONE_SLAB_DOUBLE:
0: Stone
1: Sandstone
2: Wooden
3: Cobblestone
4: Brick
5: Stone Brick
Below - not on Pi
6: Nether Brick
7: Quartz
Not on Pi
SNOW_BLOCK:
0-7: Height of snow, 0 being the lowest, 7 being the highest.
TNT:
0: Inactive
1: Ready to explode
LEAVES:
1: Oak leaves
2: Spruce leaves
3: Birch leaves
SANDSTONE:
0: Sandstone
1: Chiseled sandstone
2: Smooth sandstone
STAIRS_[COBBLESTONE, WOOD]:
0: Ascending east
1: Ascending west
2: Ascending south
3: Ascending north
4: Ascending east (upside down)
5: Ascending west (upside down)
6: Ascending south (upside down)
7: Ascending north (upside down)
LADDERS, CHESTS, FURNACES, FENCE_GATE:
2: Facing north
3: Facing south
4: Facing west
5: Facing east
[WATER, LAVA]_STATIONARY:
0-7: Level of the water, 0 being the highest, 7 the lowest
NETHER_REACTOR_CORE:
0: Unused
1: Active
2: Stopped / used up
blockEvent = mc.events.pollBlockHits()
.type
"Type of block event; there is only 1 event currently implemented BlockEvent.HIT"
blockEventType = blockEvent.type
BlockEvent types:
0: BlockEvent.HIT
.pos
"The position of the block where the event occured, i.e. the block which was hit. .pos returns a Vec3 object of x,y,z co-ordinates"
blockEventPos = BlockEvent.pos
.face
"The face of the block where the event occured"
blockEventFace = BlockEvent.face
.entityId
"entityId of the player who caused the block event, i.e. the player who hit the block"
blockEventPlayer - BlockEvent.entityId
chatEvent = mc.events.pollChatPosts()
.type
"Type of block event; there is only 1 event currently implemented ChatEvent.POST"
chatEventType = chatEvent.type
ChatEvent types:
0: ChatEvent.POST
.message
"The message which was posted to the chat window."
chatEventMessage = ChatEvent.message
.entityId
"entityId of the player who posted the message to the chat."
blockEventPlayer - BlockEvent.entityId
xPos = position.x
yPos = position.y
AIR = Block(0)
STONE = Block(1)
GRASS = Block(2)
DIRT = Block(3)
COBBLESTONE = Block(4)
WOOD_PLANKS = Block(5)
SAPLING = Block(6)
BEDROCK = Block(7)
WATER_FLOWING = Block(8)
WATER = WATER_FLOWING
WATER_STATIONARY = Block(9)
LAVA_FLOWING = Block(10)
LAVA = LAVA_FLOWING
LAVA_STATIONARY = Block(11)
SAND = Block(12)
GRAVEL = Block(13)
GOLD_ORE = Block(14)
IRON_ORE = Block(15)
COAL_ORE = Block(16)
WOOD = Block(17)
LEAVES = Block(18)
GLASS = Block(20)
LAPIS_LAZULI_ORE = Block(21)
LAPIS_LAZULI_BLOCK = Block(22)
SANDSTONE = Block(24)
BED = Block(26)
COBWEB = Block(30)
GRASS_TALL = Block(31)
WOOL = Block(35)
FLOWER_YELLOW = Block(37)
FLOWER_CYAN = Block(38)
MUSHROOM_BROWN = Block(39)
MUSHROOM_RED = Block(40)
GOLD_BLOCK = Block(41)
IRON_BLOCK = Block(42)
STONE_SLAB_DOUBLE = Block(43)
STONE_SLAB = Block(44)
BRICK_BLOCK = Block(45)
TNT = Block(46)
BOOKSHELF = Block(47)
MOSS_STONE = Block(48)
OBSIDIAN = Block(49)
TORCH = Block(50)
FIRE = Block(51)
STAIRS_WOOD = Block(53)
CHEST = Block(54)
DIAMOND_ORE = Block(56)
DIAMOND_BLOCK = Block(57)
CRAFTING_TABLE = Block(58)
FARMLAND = Block(60)
FURNACE_INACTIVE = Block(61)
FURNACE_ACTIVE = Block(62)
DOOR_WOOD = Block(64)
LADDER = Block(65)
STAIRS_COBBLESTONE = Block(67)
DOOR_IRON = Block(71)
REDSTONE_ORE = Block(73)
SNOW = Block(78)
ICE = Block(79)
SNOW_BLOCK = Block(80)
CACTUS = Block(81)
CLAY = Block(82)
SUGAR_CANE = Block(83)
FENCE = Block(85)
GLOWSTONE_BLOCK = Block(89)
BEDROCK_INVISIBLE = Block(95)
STONE_BRICK = Block(98)
GLASS_PANE = Block(102)
MELON = Block(103)
FENCE_GATE = Block(107)
GLOWING_OBSIDIAN = Block(246)
NETHER_REACTOR_CORE = Block(247)
.data
"The data (or sub-type) of a block"
Data Values of blocks:
WOOL:
0: White
1: Orange
2: Magenta
3: Light Blue
4: Yellow
5: Lime
6: Pink
7: Grey
8: Light grey
9: Cyan
10: Purple
11: Blue
12: Brown
13: Green
14: Red
15:Black
WOOD:
0: Oak (up/down)
1: Spruce (up/down)
2: Birch (up/down)
(below not on Pi)
3: Jungle (up/down)
4: Oak (east/west)
5: Spruce (east/west)
6: Birch (east/west)
7: Jungle (east/west)
8: Oak (north/south)
9: Spruce (north/south)
10: Birch (north/south)
11: Jungle (north/south)
12: Oak (only bark)
13: Spruce (only bark)
14: Birch (only bark)
15: Jungle (only bark)
WOOD_PLANKS (Not on Pi):
0: Oak
1: Spruce
2: Birch
3: Jungle
SAPLING:
0: Oak
1: Spruce
2: Birch
3: Jungle (Not on Pi)
GRASS_TALL:
0: Shrub
1: Grass
2: Fern
3: Grass (color affected by biome) (Not on Pi)
TORCH:
1: Pointing east
2: Pointing west0: White
1: Orange
2: Magenta
3: Light Blue
4: Yellow
5: Lime
6: Pink
7: Grey
8: Light grey
9: Cyan
10: Purple
11: Blue
12: Brown
13: Green
14: Red
15:Black
WOOD:
0: Oak (up/down)
1: Spruce (up/down)
2: Birch (up/down)
(below not on Pi)
3: Jungle (up/down)
4: Oak (east/west)
5: Spruce (east/west)
6: Birch (east/west)
7: Jungle (east/west)
8: Oak (north/south)
9: Spruce (north/south)
10: Birch (north/south)
11: Jungle (north/south)
12: Oak (only bark)
13: Spruce (only bark)
14: Birch (only bark)
15: Jungle (only bark)
WOOD_PLANKS (Not on Pi):
0: Oak
1: Spruce
2: Birch
3: Jungle
SAPLING:
0: Oak
1: Spruce
2: Birch
3: Jungle (Not on Pi)
GRASS_TALL:
0: Shrub
1: Grass
2: Fern
3: Grass (color affected by biome) (Not on Pi)
TORCH:
1: Pointing east
3: Pointing south
4: Pointing north
5: Facing up
STONE_BRICK:
0: Stone brick
1: Mossy stone brick
2: Cracked stone brick
3: Chiseled stone brick
STONE_SLAB / STONE_SLAB_DOUBLE:
0: Stone
1: Sandstone
2: Wooden
3: Cobblestone
4: Brick
5: Stone Brick
Below - not on Pi
6: Nether Brick
7: Quartz
Not on Pi
SNOW_BLOCK:
0-7: Height of snow, 0 being the lowest, 7 being the highest.
TNT:
0: Inactive
1: Ready to explode
LEAVES:
1: Oak leaves
2: Spruce leaves
3: Birch leaves
SANDSTONE:
0: Sandstone
1: Chiseled sandstone
2: Smooth sandstone
STAIRS_[COBBLESTONE, WOOD]:
0: Ascending east
1: Ascending west
2: Ascending south
3: Ascending north
4: Ascending east (upside down)
5: Ascending west (upside down)
6: Ascending south (upside down)
7: Ascending north (upside down)
LADDERS, CHESTS, FURNACES, FENCE_GATE:
2: Facing north
3: Facing south
4: Facing west
5: Facing east
[WATER, LAVA]_STATIONARY:
0-7: Level of the water, 0 being the highest, 7 the lowest
NETHER_REACTOR_CORE:
0: Unused
1: Active
2: Stopped / used up
BlockEvent
"The definition of a BlockEvent in Minecraft, used to describe an event in Minecraft affecting blocks; returned by the Minecraft.events.pollBlockHits() method."blockEvent = mc.events.pollBlockHits()
.type
"Type of block event; there is only 1 event currently implemented BlockEvent.HIT"
BlockEvent types:
0: BlockEvent.HIT
.pos
"The position of the block where the event occured, i.e. the block which was hit. .pos returns a Vec3 object of x,y,z co-ordinates"
.face
"The face of the block where the event occured"
.entityId
"entityId of the player who caused the block event, i.e. the player who hit the block"
ChatEvent
"The definition of a ChatEvent in Minecraft, used to describe an event when a message is posted to the chat bar in Minecraft, returned by Minecraft.events.pollBlockHits() method."chatEvent = mc.events.pollChatPosts()
.type
"Type of block event; there is only 1 event currently implemented ChatEvent.POST"
ChatEvent types:
0: ChatEvent.POST
.message
"The message which was posted to the chat window."
.entityId
"entityId of the player who posted the message to the chat."
Vec3
"The definition of a 3 part vector in Minecraft, i.e. a set of x, y, z co-ordinates; x and z are the horizontal positions, y the vertical"
position = vec3.Vec(0,0,0)
.x
"x position"
.y
"y position"
.z
"z position"
zPos = position.z
Whenever I need a place to remember the list, I'll go here!
ReplyDeleteThanks! This helps a lot!
ReplyDeleteThis is great!
ReplyDeleteAre these all of the commads that the raspberry pi minecraft has to offer if not then could someone link me to a in depth list of commands?
ReplyDeleteIm pretty sure this is a complete list. Do you think something is missing?
DeleteHi Martin, love your work. I'm wondering if there is a method to give the direction the player is currently facing. Obviously you can use position deltas to work out where someone may be facing when on the move, but if they are stationary, a Vec3 does not give directional information. Any ideas?
ReplyDeleteUnfortunately not, there isnt a api call to get the players heading. As you say you can use the players pos to find out the direction they are travelling.
DeleteYou might be interested to know I have added 'direction functions' to the Raspberry Juice plugin. Unfortunately I can add them to Minecraft: Pi edition.
DeleteIn the .pollBlockHits section you may want to add a colon ':' in that for loop. As a one-day-old python programmer it messed me up for a bit
ReplyDeleteThanks, updated.
DeleteDitto in .getPlayerEntityIds() example "for" loop - missing ":"
Delete(PS - thanks Martin for a great ressource, alongside the book! =o)
Thanks updated
DeleteHello, Martin. I'm a Japanese Minecraft user. I'm trying to gather information about Minecraft PI and add it to the website 'Minecraft Japan Wiki'. I have ever translated this page into Japanese for personal needs and want to contribue my translation to 'Minecraft Japan Wiki'. Could I ask you to permit my publishing the translation of this page on 'Minecraft Japan Wiki'? I'm looking forward to your reply.
ReplyDeleteHi, I have only just seen this comment. You have my permission to publish a translation of this page. A link back would be nice ;)
DeleteFirst of all, congratulations for the book!! Nice stuff to introduce kids in programming. I have a question, is it possible to capture the keys pressed in minecraft? The idea is not to have to run the program in order to perform some action but execute it in the beginning (while True:) and a listener to fire some actions when a key is pressed, Thanks a lot!
ReplyDeleteIts not possible to 'ask' Minecraft what keys have been pressed but you can ask the operating system (windows, linux, mac os) etc and then recreate to those keypress events. It depends on what OS you are using, but if you were using windows the PyHook module would help. http://sourceforge.net/p/pyhook/wiki/PyHook_Tutorial/. Have a google.
DeleteSomeone has ported PyHook to windows too http://jeffhoogland.blogspot.co.uk/2014/10/pyhook-for-linux-with-pyxhook.html
DeleteI'm, using Linux and I didn't think that approach!! Thanks for the reply.
DeleteOver the last two days, I've implemented most of the Raspberry Juice/PI protocol within a Forge mod for singleplayer desktop Minecraft (Raspberry Jam Mod). The most notable gap is the event handling right now, but you can draw shapes with python and have fun.
ReplyDeleteI'm pretty much new for Minecraft, and a fortiori to Minecraft modding, and I did this for my daughter to encourage her to learn python. I've tested this with 1.8 on Windows, but I assume it should work on Linux and OSX just as well.
Source and mod here:
https://github.com/arpruss/raspberryjammod/releases
Hi Alexander, looks good, another guy put a post of the adventures in minecraft forum who had done the same http://www.stuffaboutcode.com/p/adventures-in-minecraft-forum.html?place=msg%2Fadventures-in-minecraft-forum%2Fchq0v6Ka1zA%2FOxvwTFUWCXEJ
DeleteHis code is here https://github.com/kbsriram/mcpiapi
Perhaps you 2 could join forces?
Martin
Nice! And he's got support for the block hit commands.
ReplyDeleteOn the other hand, I can't get his mod working on my computer. :-(
Just bought the book! :)
ReplyDeleteGreat API.. tons of stuff for my sons Jeffery and Nathan to play around.. thanks
ReplyDeleteHey, Do I use my own 'address = "localhost", port = 4711'.
ReplyDeleteIf so where do I find it?
Thanks in Advance.
If the 'server' is running on your the same machine as your program you dont need to get an IP address or port just use:
Delete.create().
If you want to run your program on a different computer to your server you will have to tell it what the IP address of your server e.g:
.create("192.168.1.1")
Its unlikely you would ever need to use a different port (unless you have configured raspberry juice to do so.
Thanks again. Also this website is really helpful.
DeleteSorry, one more thing - I am unable to 'Join World' / Survival doesn't work.
You can only join a world if you have another Pi running Minecraft Pi edition.
DeleteThe Pi edition doesnt have survival mode, only creative. Hopefully mojang will release an update.
Thanks. Hopefully they do...
DeleteHi Martin,
ReplyDeletethanks for all the examples and API doc. Any idea how to control the range of a MCPI world? It is always 256 x 256 blocks in the xz - plane. But sometimes it runs from -128 to 127, sometimes anything else like -184 to 71. Is there a way to retrieve the range of the current world?
Thanks, Christian
Im pretty sure there isnt a way of doing this through the api. I suspect you get different co-ords because of a change of spawn point which is always 0,0,0.
DeleteMaybe you could read this information from the world file but I have no knowlegde of how or if this would work.
Found a working solution. Outside the range the block type is 95, so I just check where it changes to <>95 along the x and z axis.
DeleteHi Martin, I am new to this. Is it possible to write texts in raspberry minecraft standing sign object? Could you give a hint how to write the text in minecraft sign board object?. Thank you in advance.
ReplyDeleteGunhas
Unfortunately its not possible with the API at the moment, hopefully Mojang will give us an update to Minecraft: Pi Edition.
DeleteFirst and foremost, thanks a million for this guide, use it almost every day! We just found out you can also change the orientation (North, East, South, West) of the FENCE_GATE block. Maybe add that to the chest, ladders, and furnace section?
ReplyDeleteThank you, updated.
DeleteIs there a way to set the time through Raspberry Juice? Or a way to send commands programmatically to the server shell like "time set 1"?
ReplyDeleteUnfortunately not.
DeleteCan I code to hit a block?
ReplyDeleteYou can use the api to get the blocks that have been hit, but you cant use the api to simulate a player hitting a block.
DeleteIt would be interesting if API allow to manage player.
ReplyDeleteIn example, if Minecraft.player would have setRotation, users could program a player rotation 90 degrees each second, or another action like moveForward to do a loop to move 10 blocks, or use pickaxe get a block or build a small vegetable garden...
Interesting because I didnt find something similar, and I would like to do some macros to mine, and build bridges using materials in survive mode, not only creating in creative mode. It would be very powerful to learn scripting and make cool things.
If help is needed maybe I could do something.
Hey Martin! I love all the minecraft programming information you provide! I have been able to make so many cool programs with it. I was wondering if there was a way to find the block below the player to do an action? Thanks!
ReplyDeleteI dont really understand your question. You can find out what block is below a player. What do you mean by 'to do an action'?
DeleteThanks for Repling Martin! How do you find out what block is below the player. I am making a program where it will print different messages to the chat depending what block is below the player. Thanks Again!
DeleteI figured out how to spawn entitys (cow, sheep, pig, etc) using python, but I don't know how to spawn monsters on MCPI. Is there a way, and if so, how? Thanks!
ReplyDelete1. How do you spawn entities?
Delete2. Can I control the entities actions? Like low lvl AI flocking / path planning
How are you spawning entities?
DeleteHi guys, I wrote a small python script to spawn any mobs on Minecraft Pi worlds by updating your entities.dat file.
DeleteCheck this out on my repository :
https://github.com/Will-777/spawn_mobs_mcpi
Cheers !
Hello,
ReplyDeleteI'm trying to code using the minecraft API. my config is that the minecraft server is running on a raspberry PI 2 but the game (and player) is started from a mac connected on the same LAN. I try to do simple getBlock calls but I receive an error : File "/home/pi/ServeurMinecraft/myScripts/mcpi/minecraft.py", line 123, in getBlock
return int(self.conn.sendReceive("world.getBlock", intFloor(args)))
ValueError: invalid literal for int() with base 10: ''
even simple postToChat calls are not working...
Any idea to help?
The Minecraft - Pc Edition does not support such things.
DeleteThe Python library is for the minecraft - Pi Edition.
You can use the Raspberry Juice plugin for full minecraft so you can use the same API as Minecraft: Pi Edition
DeleteGreat stuff!But one easy qustions:
ReplyDeleteIf one raspi joins to world ofca second raspi then the Coding must be MC.create(ipraspi,4711) for the one who joines and
MC.create() for the other one?
DieOma
Yes
DeleteThis comment has been removed by the author.
ReplyDeleteMartin,
ReplyDeleteAwesome stuff here. I've been adjusting the public API and adding a PEP8 compliant interface. Python devs will appreciate that more than the camelCase stuff.
On another note, as I'm using this to teach my daughter Python, we've discovered that we can't make torches stick to the walls. I can set torches that are pointed straight up, but when I use any other directions, the torch pops right off.
I can even query a manually placed torch and get this as a response: Block(50, 4), but if I try to create such a block, it doesn't stick.
Any ideas?
Cheers,
David
Re torches. I have struggled in the past. From what i remember, you just create them next to a wall or floor and the game itself decides what to stick them too.
DeleteThis is my code for attaching a torch to a block
Deletemc.setBlock(69, 80, 0, block.GOLD_BLOCK)
mc.setBlock(70, 80, 0, block.TORCH.id, 1) # 1 = east (towards +ve x)
mc.setBlock(68, 80, 0, block.TORCH.id, 2) # 2 = west (towards -ve x)
mc.setBlock(69, 80,-1, block.TORCH.id, 4) # 4 = north (towards -ve z)
mc.setBlock(69, 80, 1, block.TORCH.id, 3) # 3 = south (towards +ve z)
mc.setBlock(69, 81, 0, block.TORCH.id, 5) # 5 = up (towards +ve y)
This comment has been removed by the author.
ReplyDeleteThe item data can be tricky. The information returned from a query is a sequence of variables, not an array. Thus you can use (with added indentations...):
ReplyDeletewhile True:
blocktype,data=mc.getBlockWithData(x,y-1,z)
if blocktype==35 and data==1:
mc.postToChat("Standing on orange wool")
Is there a "Cheat Sheet" version of this page?
ReplyDeleteOne that I could print, and provide to the kids.
This comment has been removed by the author.
ReplyDeleteI wander why I cat get other block ID in block.py(folder MineAdventures)? like SPRUCE_WOOD_PLANK,REDSTONE.I have tried to add some block id in block.py(folder mcpi)such as[POLISHED_DIORITE=Block(1,4)],[DARK_OAK_WOOD_PLANK=Block(5,5)].But it is unworkable, when I run code like【mc.setBlock(pos.x,pos.y,pos.z,block.BIRCH_WOOD_PLANK.id)】,Minecraft still tell me I was running Oak Wood Plank. How can I perfect The block.py(mcpi) to easier to use before.
ReplyDeleteChinese 17 boy, hope you don't mind my English.
Thanks for the guide, plan to buy your book as the kids learn more..
ReplyDeletequestion: is there a way to write an if loop that takes input from the keyboard... if 'w' key is pressed, drop a flower at playerPos?
getPos, getTilePos, setPos and setTilePos all appear to be relative to the player's spawn point at least in a single player world. I am going through trying to teleport my character but the coordinates I end up on are not the world's coordinates but a coordinate relative to where my character would spawn.
ReplyDeleteI'd love to be able to teleport to a specific world coordinates by cannot. Can anyone assist?
Positions in minecraft are absolute, its just that in Minecraft: Pi edition the centre of the world is 0, 0, 0. If your using Raspberry Juice, it simulates this for you.
DeleteI'd be grateful for a couple of sentences on how the coordinates returned by mc.player.getTilePos() compare with what's shown on the F3 debug screen on PC Minecraft.
DeleteThe co-ords returned my getTilePos are relatively to the spawn position. If you minus the spawn pos from the pos shown on f3, you get the co-ords returned by getTilePos.
DeleteThanks. Based on your info, I was expecting that either sleeping in a bed or calling /spawnpoint on the client would zero out the Python getTilePos(); it didn't have any effect for me.
DeleteI also assume that there's no method on the Python API to return the player's spawn point?
Am I right in saying that there's no Python code I can run to reliably print the coordinates that the user will be seeing in the F3 debug screen? If so, I'll just use mc.postToChat(pos) to let the user know where they are according to Python. That way, the user can write some simple scripts with hardcoded locations (rather then doing everything relative to their current position with mc.player.getTilePos()).
Sorry if I'm missing something obvious!
I was missing something obvious ;) I thought you were referring to a player's spawn point as I didn't know that a "world spawn point" existed. I learned about it here:
Deletehttp://minecraft.gamepedia.com/Spawn/Multiplayer_details
Issuing this command in the Minecraft terminal makes things tie up perfectly for me:
/setworldspawn 0 0 0
After that, I get the same info on the F3 debug screen and reported by Python's getTilePos(). No extra thought required. Nice.
Other details:
If one didn't want to set the spawn point to 0 0 0 for some reason, and the spawn point is unlikely to be changed by an admin user, it would just be a one-time effort to get the required offsets for Python. That way, though, you'd need some extra Python code to help the user not have headaches. The only way to get at the world spawn point seems to be to look at level.dat (unzip then look for SpawnX, SpawnY, SpawnZ or use the "NTBExplorer" utility). There isn't a more helpful /getworldspawn on Vanilla Minecraft so it's not fair to ask Python to know the values automatically.
This comment has been removed by the author.
ReplyDeleteThis comment has been removed by a blog administrator.
ReplyDeleteHellow Martin,I did try Adventure 5 the first step to let my LED flash(LEDtest.py) on bread board, But it was useless.I dont know why.i checked it,software is ok,LED...I am not sure,if i just energize Arduino,LED shine.when i run“LEDtest.python”,LEDs was lighting,and only flashing which yellow on Arduino but not the bigger one.that is not like book what the book says.what's going on?
ReplyDeleteI was wondering how to specify which type of block you want to use in the setBlock function. I want to populate my world with tall grass except it sets the wrong type of GRASS_TALL. How do I use .data to do that?
ReplyDeletesimply:
Deletemc.setBlock(x,y,z,block.GRASS_TALL.id, 1)
the final parameter 1 is the type of tall grass.
getPos is return as not defined.
ReplyDeletefrom mcpi.minecraft import Minecraft
mc = Minecraft.create()
pos = mc.player.getPos()
Why?
Hi everyone!
ReplyDeleteI'm looking for a link to minecraft.py file from this lib where the method
.getPlayerEntityId(playerName)
exists
Can anyone help with link?
Thanks in advance
This is the python 3 library which is used on Raspbian
Deletehttps://github.com/py3minepi/py3minepi/blob/master/mcpi/minecraft.py
Hi Martin!
DeleteTnx for reply. Can't find such method there .getPlayerEntityId(playerName)
I see only # def getPlayerEntityIds(self) and it returns list of entity ids.
I'm interested in method which gets the ID of player by nickname
Its written in article that such method exists...
Is it some mistake?
Hello!
DeleteI've added this method to mcpi
https://github.com/pa7lux/python-minecraft-lib/blob/master/mcpi/minecraft.py
getPlayerEntityId(self, name) it takes nickname and returns entity id.
Very useful method for coding on public servers. Using it you can easily make scripts for any of player on your public server.
Can I see an example of an block ID with a .data extension? I’m trying to rotate some stairs by using the block ID 108.3, but to no avail. What would I need to do to have the ID make the block rotate?
ReplyDeleteYou dont say what platform you are working on but stairs arent 103 on the Pi.
DeleteAnyway, for cobblestone stairs, I would use:
mc.setBlock(x, y, z, block.STAIRS_COBBLESTONE.id, 3)
Im on a raspberry pi, on minecraft pi.
DeleteI tried what you said, but this error message came up.
Traceback (most recent call last):
File "/home/pi/MinecraftHouse", line 1201 in
mc.setBlocks(x1, y1, z1, x2, y2, z2, block.STAIRS_COBBLESTONE_.id, 3)
NameError. name 'block' is not defined.
For every block in this code, I have used the their block id. Whenever I try to put a block in that format, it brings this error message, which is why I posted my message in numbers. Im pretty sure block ID 108 is stair bricks, and I was hoping the ".3" would make them ascend in a different direction.
I solved this problem by putting the comma and number after the id.
DeleteE.g 53, 1 would make my wooden stairs point in a different direction.
This comment has been removed by the author.
ReplyDeleteThis comment has been removed by the author.
DeleteHi, I am trying to use mcpi to control MC, but .getPlayerEntityId(playerName) method not working (Minecraft instance has no attribute 'getPlayerEntityId'). Did I use the wrong mcpi package? How could I get the user object by username? Thanks for your reply!
ReplyDeleteI found the modded API from this repo zhuowei/RaspberryJuice. Thank you for the good tutorial.
DeleteHi, I have a strange problem when 2 users are logged in to the server and running python code.
ReplyDeletee.g. user1 runs this code>> mc.player.setTilePos(0, 65, 0) and instead of user1 teleporting, user2 teleports instead
and when user1 runs the code for mc.player.getTilePos(), it returns the position of user2
BUT... when user2 runs the above code, it runs nicely for user2
Am I doing something wrong? Just wondering if there's a best practice guide for when you run a server with multiple players who are all running python scripts
mc.player always refers to the 'host' player - i.e. the player who's game it is.
DeleteIf you want to do multi player you need to look at the mc.entity functions which allow you to specific which entity (player) to work with.
Thanks for the quick reply!
DeleteWould that also mean that user1 can write code to affect user2 using the entityid? i.e. user1 can teleport user2 ?
Is there a way to prevent this? I'm running a class for kids, and I can imagine my kids running amok with so much power :)
Yes any program connecting to the server can change any entity.
DeleteWhat platform are you using?
i see, the students are using win10 machines, and the server is running spigot (pretty new to this, so I'm not sure if that's the same as raspberry juice)
DeleteThanks so much for your response, love your website!
This comment has been removed by the author.
ReplyDeleteI can't seem to get mc.entity.SetPos() working correctly. I have the correct EntityID, and when I teleport the other player, I can see them in the new location. Seems good.
ReplyDeleteHOWEVER, on that user's own screen, they have not been moved! And if that user moves their character in anyway, they vanish on MY screen and go back to their original location (which it seems they never actually left).
Any ideas?
Are you using Minecraft Pi edition? If so unfortunately there is a bug with Minecraft itself which means it doesn't work.
DeleteGreat guide!
ReplyDeleteIs there any way you could work out which direction a player is facingon the raspberry pi e.g. north, south, east, west
Thanks
Also when placing a door using python, you only get the bottom half of the door...
DeleteYou need to place both halves of the door individually.
Deletemc.setBlock(x,y,z,block.DOOR_WOOD.id,0)
mc.setBlock(x,y+1,z,block.DOOR_WOOD.id,8)
I haven't worked out how to set a double door yet with hinges on outside.
Here is code to place a double door with hinges on outside.
Deletemc.setBlock(x,y+1,z,block.DOOR_WOOD.id,4)
mc.setBlock(x,y+2,z,block.DOOR_WOOD.id,8)
mc.setBlock(x+1,y+1,z,block.DOOR_WOOD.id,1)
mc.setBlock(x+1,y+2,z,block.DOOR_WOOD.id,8)
If one player hides diamonds and gives hints about the coordinates ...
ReplyDeleteIt seems to be useless for other players...
Is there a possibility for hide_and_find games?
Hi, Martin, great job!
ReplyDeleteOne question, is there a way to know, which object (for ex. cobblestone, dirt, daimond e.t.c.) payer holds in his hand?
Thanks
Hi, Martin, great job!
ReplyDeleteOne question, is there a way to know, which object (for ex. cobblestone, dirt, daimond e.t.c.) payer holds in his hand?
Thanks
Unfortunately not :(
DeleteI have the minecraft software running 1.9.
ReplyDeleteI have spigot server running 1.9. I can connect to the serve via minecraft. I can control the server via spigot.
I have the latest mcpi installation with python 3.5
I can successfully run all the minecraft commands in python (no error output) but I don't get any results. I can connect in python and send / receive data but something's clearly not working. Any ideas?
You do say so... Have you got the RaspberryJuice plugin installed?
DeleteThis comment has been removed by the author.
DeleteThis comment has been removed by the author.
DeleteRaspberryJuice was not loading.
DeleteAfter poking through the spigot logs I noticed this error near the very top which I had not noticed before.
Could not load ‘plugins/RaspberryJuice.jar’ in folder ‘plugins’
org.bukkit.plugin.InvalidPluginException: java.lang.UnsupportedClassVersionError: net/zhuoweizhang/raspberryjuice/RaspberryJuicePlugin : Unsupported major.minor version 52.0
The key information is ‘version 52.0’ from the Java Class File you can see that requires 1.8
https://en.wikipedia.org/wiki/Java_class_file
I was running Java 1.6 and RaspberryJuice.jar was compiled (requires?) 1.8. Once I updated Java and changed the port back to 4711 in minecraft.py everything is working normally.
This comment has been removed by the author.
ReplyDeleteHi, We bought my daughter your adventures in Minecraft book at Christmas - she has the bukkit server setup along with RaspberryJuice on her laptop (using the link on the 'Wiley' website) and she is successfully following through the examples and adapting them to her own ideas (and having lots of fun with it :)), however she has tried referencing other players on her server, instead of just herself (i.e. for the geofencing example) - when others are connected to her server, the getPlayerEntityIds() noted in the list above gave an error. I updated to the latest version of the bukkit server (1.11.2) and the latest RaspberryJuice plugin (1.8), and this is now working, however there is no easy way to see which player is herself or which is others on the server, so we tried using getPlayerEntityId("PlayerName"), but this gives an error: "AttributeError: Minecraft instance has no attribute 'getPlayerEntityId'" - the list above suggests this should work with Raspberry Juice. can you advise where we might be going wrong please? - thanks...
ReplyDeleteHi,
DeleteIm pleased you daughter is enjoying Adventures in Minecraft.
I suspect you problem is that you dont have an updated version of the python library which includes the additional functions for the extra functions which come with RaspberryJuice.
You can find it in the Raspberry Juice repo on GitHub:
https://github.com/martinohanlon/RaspberryJuice/tree/master/src/main/resources/mcpi/api/python/modded/mcpi
Let me know how you get on.
Martin
Thanks for your work, Martin. Two questions.
ReplyDelete1. Is the repo for Raspberry Juice in the previous comment the latest source for the mcpi library? Or does it exist on its own elsewhere?
2. Is the Mojang API to Minecraft documented somewhere? I've not been able to find it. I'd like to know whether it's possible to extend the work you've done here to include things like mining a block (producing a drop) instead of just setting the block to a different id. This would be useful in something like an automatic mining script.
Thanks again.
1. Well its the latest source for the library which works with the extensions in RaspberryJuice, there are other versions, created by other people, but they probably dont work with the RaspberryJuice extensions.
Delete2. The api was only documented (poorly) in a text file distributed with Minecraft: Pi edition, a little while ago I pulled this information together into a github repo https://github.com/martinohanlon/Minecraft-Pi-API/blob/master/api.md - this is the most complete description of the api I've seen.
I am trying to use .getDirection(), but whenever I try to use it I get this error message:
ReplyDeleteAttributeError: 'CmdPlayer' object has no attribute 'getDirection'
Has .getDirection() been changed to a new name or been removed?
To use the extended features in RaspberryJuice you will need an update mcpi library https://github.com/zhuowei/RaspberryJuice/tree/master/src/main/resources/mcpi/api/python/modded/mcpi
DeleteHi theren, I've just forked the https://github.com/zhuowei/RaspberryJuice project to add setEntity method to the api. You need to compile the plugin and then you can add new entities, mobs, animals, villagers with python code (https://github.com/pxai/RaspberryJuice)
ReplyDeleteI am having issues writing a program. The program is supposed to place 3 wool blocks (red, blue, and green). Then when I put a torch on red, for example, it activates a GPIO pin and turns an RGB LED red. Then if I put a torch on other colors, it will activate the LED accordingly.
ReplyDeleteI have not written the GPIO stuff in just yet, but I am testing with a loop and print. So that when I execute the code with a torch on red, it prints red, red, red... etc. If I execute the code with red and blue, it prints red, blue, red, blue... etc.
The problem is, if I place or remove torches while playing inside the world, the loop and print will not detect the change. How can I get it to recognize a change in the presence of blocks, such as torches? Ideally, I would like to place a torch on blue in-game and have my LED light up blue. Then destroy the torch and put it on red, and have the LED change to red. Any thoughts?
Hi Merlyn. You haven't posted the code that you're using to check for the torches, so it's worth checking that you understand that a torch is a whole block in the Minecraft world. Adding a torch block next to a wool block doesn't modify the wool block in any way. This is a little counter-intuitive as it looks like the torch is *attached* to the wool block.
DeleteIf your wool block is at coordinates x, y, z and you're only interested in checking for torches attached to the sides of the wool block (not the top or bottom) then you should use:
import mcpi.minecraft as minecraft
import mcpi.block as block
mc = minecraft.Minecraft.create()
print mc.getBlock(x + 1, y, z ) == block.TORCH.id or \
mc.getBlock(x - 1, y, z ) == block.TORCH.id or \
mc.getBlock(x , y, z + 1) == block.TORCH.id or \
mc.getBlock(x , y, z - 1) == block.TORCH.id
I deleted my post earlier, because it was through my phone and it wasn't showing proper indents. Here is my code again. I will put >>>> everywhere indents are present (replying won't let me indent):
Delete# Minecraft libraries
import mcpi.minecraft as minecraft
mc = minecraft.Minecraft.create()
# Find player position
x, y, z = mc.player.getPos()
# Commonly used Minecraft variables
red = 14
green = 13
blue = 11
air = 0
obsidian = 49
wool = 35
torch = 50
# variable evaluate the space above wool blocks.
torchRed = mc.getBlock(x + 3, y, z - 1, x + 3, y, z - 1)
torchGreen = mc.getBlock(x + 3, y, z, x + 3, y, z)
torchBlue = mc.getBlock(x + 3, y, z + 1, x + 3, y, z + 1)
# Creates target platform
def targetArea():
>>>>mc.setBlocks(x + 2, y - 1, z - 2, x + 4, y + 10, z + 2, air)
>>>>mc.setBlocks(x + 2, y - 1, z - 2, x + 4, y - 10, z + 2, obsidian)
>>>>mc.setBlocks(x + 3, y - 1, z - 1, x + 3, y - 1, z - 1, wool, red)
>>>>mc.setBlocks(x + 3, y - 1, z, x + 3, y - 1, z, wool, green)
>>>>mc.setBlocks(x + 3, y - 1, z + 1, x + 3, y - 1, z +1, wool, blue)
# these are test blocks that place a torch above red, green, and blue
# wool blocks. Commment them on or off as desired.
>>>>#mc.setBlocks(x + 3, y, z - 1, x + 3, y, z - 1, torch, 1)
>>>>mc.setBlocks(x + 3, y, z, x + 3, y, z, torch, 1)
>>>>#mc.setBlocks(x + 3, y, z + 1, x + 3, y, z + 1, torch, 1)
targetArea()
# if variables find a torch above wool blocks, it will print the color.
# print('color') will be later replaced to activate a GPIO pin.
# for now, these are just used to test that Minecraft detects a change from
# within game. Presently, for some reason it does not. It will only detect
# the torches placed by mc.setBlocks(....)
while True:
>>>>if torchRed == torch:
>>>>>>>>print('red')
>>>>if torchGreen == torch:
>>>>>>>>print('green')
>>>>if torchBlue == torch:
>>>>>>>>print('blue')
This comment has been removed by the author.
ReplyDeleteHere's a Gist with some code that works and some comments. Remember, we're all beginners! :)
Deletehttps://gist.github.com/daveboden/21cfafdbe4513df7eca501c157019cf4
Thank you Dave, I will try it tonight!
DeleteThe program now works correctly. There was a block of code that checked to see if a torch was present or absent. Although this worked, it needed to be placed INSIDE the loop to be checked continuously. Below is the working code. Next step is to add GPIO functionality. Remember, >>>> means indent. However, the formatting of this post does not allow indents. So when you place it in your own code, replace >>>> with an indent and >>>>>>>> with 2 indents.
ReplyDelete# Find player position
x, y, z = mc.player.getPos()
# Commonly used Minecraft variables
red = 14 # parameter of the wool block
green = 13 # parameter of the wool block
blue = 11 # parameter of the wool block
air = 0 # used to displace terrain and trees created above the platform
obsidian = 49 # used to create an aesthetic border around colored wool blocks
wool = 35 # plain wool block
torch = 50 # will be used as the mechanism to turn on GPIO pins in a future version of this program
# Creates target platform. Basically 3 colored wool blocks (red, green, blue), surrounds them with
# an obsidian border, and clears the space above the platform. This is created relative to
# player position.
# mc.setBlocks places blocks in the Minecraft API using X,Y,Z coordinates, block types and parameters.
def targetArea():
>>>>mc.setBlocks(x + 2, y - 1, z - 2, x + 4, y + 10, z + 2, air)
>>>>mc.setBlocks(x + 2, y - 1, z - 2, x + 4, y - 10, z + 2, obsidian)
>>>>mc.setBlocks(x + 3, y - 1, z - 1, x + 3, y - 1, z - 1, wool, red)
>>>>mc.setBlocks(x + 3, y - 1, z, x + 3, y - 1, z, wool, green)
>>>>mc.setBlocks(x + 3, y - 1, z + 1, x + 3, y - 1, z +1, wool, blue)
# Used for testing. these are test blocks that place a torch above red, green, and blue
# wool blocks. Commment them on or off as desired.
>>>>mc.setBlocks(x + 3, y, z - 1, x + 3, y, z - 1, torch, 1)
>>>>mc.setBlocks(x + 3, y, z, x + 3, y, z, torch, 1)
>>>>mc.setBlocks(x + 3, y, z + 1, x + 3, y, z + 1, torch, 1)
targetArea()
# If a torch exists above a wool block, it will print the color.
# print('color') will be later replaced to activate a GPIO pin.
# for now, these are just used to test that Minecraft detects a change from
# within game.
while True:
# Evaluates if the space above wool blocks contains a torch.
# This section was moved. Originally, I wrote this above the # Creates target platform section.
# The problem was that this needed to be inside the while true loop to be continually evaluated.
# Problem solved!! :-)
>>>>torchRed = mc.getBlock(x + 3, y, z - 1, x + 3, y, z - 1)
>>>>torchGreen = mc.getBlock(x + 3, y, z, x + 3, y, z)
>>>>torchBlue = mc.getBlock(x + 3, y, z + 1, x + 3, y, z + 1)
>>>>if torchRed == torch:
>>>>>>>>print('red')
>>>>if torchGreen == torch:
>>>>>>>>print('green')
>>>>if torchBlue == torch:
>>>>>>>>print('blue')
Hi Martin,
ReplyDeleteIm trying to write a program to ask a question using the postToChat() function and then read the response from the chat window?
Thanks for any help you can give
Peter
Hi,
DeleteIf you are using the full version of Minecraft (i.e. not Minecraft Pi edition) you are in luck and can use pollChatPosts() which will return you all the messages which have been posted to the chat. Unfortunately this isnt available on the Pi edition.
Martin
Hello. I am trying to post a random math problem to the MC chat and require the player to answer it before time runs out (10 seconds).
ReplyDeleteIs this possible? If so, how can I compare that text entered in chat with the actual answer? More specifically, how does one record or capture the text entered into chat?
I also am having trouble making a cube of TNT. I want it to explode if the player runs out of time.
Here's what I have so far: https://repl.it/GLBS
Thanks in advance!
Jason
You need to pollChatPosts each time around the loop, as it returns the chats which have been posted since the last time it was run.
DeleteI made a few changes to your program, I doubt it'll work, but it should give you an idea of what you need to do.
https://repl.it/GLBS/1
I had some trouble with setBlocks and setblock, but setBlock worked just fine.
DeleteI created a pillar of TNT, dirt, and Lava (stationary), hoping that the replacing the dirt with air on a game failure would result in the TNT detonating due to the falling lava, but the lava just flows down and covers the TNT. A regular block of lava just starts flowing and no explosion. Any ideas how to ignite the TNT automatically?
Also pollChatPosts() still won't work for me:
chatposts = mc.events.pollChatPosts()
AttributeError: CmdEvents instance has no attribute 'pollChatPosts'
Thanks again!
Jason
You dont say what platform you are using? Is it a Raspberry Pi or RaspberryJuice on a PC? If Pi, it doesnt support pollChatPosts. There are icons next to each function call which describe what system it is supported on. If you are using RaspberryJuice you will need an updated version of the python library, as it missing the pollChatPosts function so it must be pretty old.
DeleteRe TNT, I have never found a way of auto igniting it on a Pi, however on PC I have just created a redstone torch next to it.
If I need to make explosions, I tend to just create a sphere of air around the TNT which achieves the same thing.
I am using a Pi, but if I understand correctly there is a Raspberry icon next to pollChatPosts.
DeleteI will try the sphere of air technique with the TNT.
Thanks for all of your help! I appreciate it! :)
Ha, turns out im not infallible! pollChatPosts only works on RaspberryJuice. I've updated the post above.
DeleteIf you want to draw spheres, check out the MincraftDrawing class in https://github.com/martinohanlon/minecraft-stuff , there is a convenient drawCircle function.
Thanks again for all of your help! I appreciate all that you do for the MC & Pi communities!
DeleteNow if someone would just update MC Pi from its humble Alpha version...! :)
Is there a way to trigger the blockHit function with something other than a sword?
ReplyDeleteNo, sorry.
DeleteHi Martin, I was wondering if you had any advice as to how to best update the RaspberryJuice PC API with the Pi functionality once it's been installed on a computer. I've been replacing it piecemeal because replacing all the files seems to produce an error, but I have to think there's an easier way to go about this...
ReplyDeleteFor anyone looking, there's two factors to consider if the Python API isn't updating properly: have the most up-to-date RaspberryJuice plugin (mine was somehow missing after some server updates) and make sure you're using the right Python API(2.x https://github.com/zhuowei/RaspberryJuice/tree/master/src/main/resources/mcpi/api/python vs 3.x https://github.com/shawill/py3minepi).
DeleteHello. I got a question. I made my own minecraft server with spigot and Hamachi, and I tried to connect to the server as I wrote down a code line 'mc = minecraft.Minecraft("25.--", 25565)'. It seemed like python run this code without an error message but there was nothing changed in minecraft. Do you recognize this problem? Is this because of Hamachi? Thank you in advance for your help.
ReplyDeleteProbably the port has to be 4711
DeleteThe port does have to be 4711, this is the port that RaspberryJuice listens on, have you included the RaspberryJuice plugin on your server?
DeleteUh, is there any risks when I set up opening Windows firewall for this port? As far as I know this 4711 port is eMule port, so I'm a little concerned.
DeleteThere are risks with everything! Opening any port will allow connections to that port. The risk, to me, seems relatively small, you are only opening a single port, which can only talk to Minecraft. You make your own choice tho.
Delete#constructs a 4interjoining walls i.e a room
ReplyDelete#To change the height and width of wall change the values of 10
from mcpi.minecraft import Minecraft
mc = Minecraft.create()
x,y,z = mc.player.getPos()
mc.setBlocks(x,y,z+1,x,y+10,z+10,45)
mc.setBlocks(x,y,z,x+10,y+10,z,45)
mc.player.setPos(x+10,y,z+10)
x,y,z = mc.player.getPos()
mc.setBlocks(x,y,z,x-10,y+10,z,45)
mc.setBlocks(x,y,z,x,y+10,z-10,45)
mc.player.setPos(x-10,y+10,z-10)
x,y,z = mc.player.getPos()
mc.setBlocks(x,y,z, x+10,y,z+10,1)
Is there a way to print minecraft commands through Python? Like
ReplyDeletemc.postToChat('/kill 90Mr_Kot90')
P.S. I am a child
No, unfortunately not.
DeleteThanks! But I still have two problem :
ReplyDelete1.how to give a player a permission to cheat in game?I try to change permissions.yml.But can't run appropriately.And I can't find Canarymod folder or config\worlds\default\default_NORMAL.cfg
2.I decide to make a program to change weather and time in game as same as the real world,I'm confused how to change them with python?e.g.When you are living in Beijing and weather is raining,in minecraft world it is also raining.
Any suggestions on how to get the biome associated with a current block? It seems the code in java would be:
ReplyDeleteBiomeGenBase biome = world.getWorldChunkManager().getBiomeGenAt(x, y);
but I think your API only shows how to set settings, not read them.
I tried to mod the RemoteSessions.java code before building with maven to expose that using:
} else if (c.equals("world.getBiome")) {
Location loc = parseRelativeBlockLocation(args[0], args[1], args[2]);
Biome biome = world.getBiome((int)loc.getX(), (int)loc.getZ());
send(biome);
but I'm not able to call 'mc.getBiome(...)' from my python console. Any suggestions on how I get that accessible?
Ok... In simply terms the Minecraft Pi edition API doesnt support it.
DeleteIt sounds like you have tried to mod RaspberryJuice to add it in. In order to call your new mod in RaspberryJuice you will also need to modify the python library to know how to call it.
The modded python library for Raspberry Juice is here:
https://github.com/zhuowei/RaspberryJuice/tree/master/src/main/resources/mcpi/api/python/modded/mcpi
Could someone explain me how to use several data values in block?
ReplyDeleteFor example, in placing trapdoor, i want to check "facing" and "half" data values... have tried this syntax:
mc.setBlock(x,y,z,96,[1,8]) or mc.setBlock(x,y,z,96,[8,1])
but it seems that only first value is working, second is ignoring...
Thank you.
Also, can't i place mobs via API?
DeleteIf you are using the Pi edition, no you cant place mobs, if you are using RaspberryJuice - use spawnEntity - i'll update the api reference above at some point!
DeleteRe data types, you need to do a bitwise AND to send 2 numbers.
I havent tried but something like:
mc.setBlock(x,y,z, 96, 8 & 1)
When i try to use the bow,I can't shoot the arrow out. Can u tell me what is happening? Thank you
ReplyDeleteAre you using the Pi edition? If so, the bow and arrow has never worked on the Pi edition.
DeleteAnd I can't also import in the minecraft name to Python. Every time i type this, from mcpi import minecraft , it says it can't import the minecraft name
ReplyDeletefrom mcpi.minecraft import Minecraft
Deletemc = Minecraft.create()
mc.postToChat("hi")
Remember that capital letters are important.
So I can't do any commands on Python 3
ReplyDeletep.s I am also a child
Do I need to start with from mcpi import minecraft?
ReplyDeleteYes, that is what I use for my Python 3.5.3 Shell.
ReplyDeleteCorrect error in "Minecraft.entity"
ReplyDeleteWrong: mc.player.setPos(entityId,0.0,0.0,0.0)
Correct: mc.entity.setPos(entityId,0.0,0.0,0.0)
Wrong: mc.player.setTilePos(entityId,0,0,0)
Correct: mc.entity.setTilePos(entityId,0,0,0)
Is there possibility to send a MC command from python code?
ReplyDeletefor example to set time or change gamemode? or just set worldspawn? this could be helpfull and give more fun for kids who wants to play and learn code.
Agreed
DeleteHow do I place beds using code? They always seems to be instantly dropped on the ground.
ReplyDeleteThis is awesome. I am having trouble with mc.pullChatPosts(), I am trying to pull my users input, but the returned list is empty. Is there any examples on how to use this function. I'm also using the full version of mine craft and I believe to have the modded mcpi. Thxs
ReplyDeleteUpdate I solved my problem! I was posting messages wrong-_-.. Typical ID10it error!
DeleteIs this the official location to get the RaspberryJuice Spigot plugin? It seems to be owned by someone else. https://github.com/zhuowei/RaspberryJuice.
ReplyDeleteYes, zhuowei originally created RaspberryJuice.
Delete