Interactive (frozen)#
These classes are for building by hand: a player in the game works together
with an IPython session started by mciwb shell. They place signs and
levers that run Python functions, follow a player around, and copy and
paste regions that the player marks out.
Note
This side of mciwb is frozen. It works and it is tested, but it is
no longer being developed, and scripts run with mciwb run are now
the main way to use mciwb. For new work use Iwb and the
builders.
A player in the world, with their position and the way they are facing. |
|
A background thread that calls a list of functions again and again. |
|
A lever, button, pressure plate or tripwire hook that calls a function. |
|
Watch for command signs placed by one player, and call a function for each. |
|
Select a box of blocks in the world, then copy, fill or clear it. |
|
Draw walls between pairs of points in the world. |
|
Build walls interactively with command signs. |
|
Convert SNBT text, such as the reply to |
Players#
- class mciwb.Player(name)[source]#
A player in the world, with their position and the way they are facing.
Each property asks the server when it is read, through the client of the calling thread (see
get_client()), so the values are always current and nothing is cached.Creating a Player sends nothing to the server and does not check that the player exists. Call
setup()to make the player an operator in creative mode (add_player()does this).- Parameters:
name (str) -- The name of the player, or the
CustomNameof any other entity, such as an armour stand. If several entities have the name, the server picks one.
Example:
from mciwb.imports import Player player = Player("Steve") print(player.pos, player.facing)
- name#
The name of the player or entity, as passed to the constructor.
- setup()[source]#
Make the player an operator in creative mode.
Runs the
opandgamemode creativecommands for the player, so that they can use command signs and build freely. Only works for a real player, not for another kind of entity.
- property inventory: list[str]#
The player’s inventory, as the server’s reply to
data get.Despite the annotation, this is one string, not a list: the raw reply to
data get entity <name> Inventory, such asSteve has the following entity data: [{Slot: 0b, id: "minecraft:oak_sign", count: 1}]. Pass it toparse_nbt()to get a list of dictionaries, one for each occupied slot.Only works for a real player who is in the game. For anything else the string is the server’s error message:
PlayerNotInWorldErroris not raised.
- property pos_f: Vec3#
The player’s exact position, with fractional coordinates.
This is the position of the player’s feet.
- Raises:
PlayerNotInWorldError -- If the player is not found in the world.
- property pos: Vec3#
The position of the block that the player’s feet are in.
This is
pos_fwith each coordinate rounded down to a whole number.- Raises:
PlayerNotInWorldError -- If the player is not found in the world.
- property facing: Vec3#
The compass direction that the player is facing, as a unit vector.
The player’s yaw is rounded to the nearest of the four compass points, and whether they look up or down is ignored. The result is one of the
Directionconstants:Direction.NORTH, which isVec3(0, 0, -1)Direction.SOUTH, which isVec3(0, 0, 1)Direction.EAST, which isVec3(1, 0, 0)Direction.WEST, which isVec3(-1, 0, 0)
So
player.pos + player.facing * 3is the block three blocks in front of the player.- Raises:
PlayerNotInWorldError -- If the player is not found in the world.
- property rotation: tuple[int | str, int | str] | str#
The way the player is looking, as
(yaw, pitch)in degrees.Despite the annotation (an mcipc type for the arguments of commands), the value is always a tuple of two floats, as Minecraft stores them. The yaw is the compass bearing, from -180 to 180: 0 is south, 90 is west, -90 is east and 180 or -180 is north. The pitch is from -90, looking straight up, to 90, looking straight down.
- Raises:
PlayerNotInWorldError -- If the player is not found in the world.
- player_in(volume)[source]#
Check whether the player is inside a volume.
- Parameters:
volume (Volume) -- The volume of blocks to check.
- Returns:
True if the block that the player’s feet are in (
pos) is in volume, counting the blocks of its faces.- Raises:
PlayerNotInWorldError -- If the player is not found in the world.
- Return type:
- classmethod players_in(volume)[source]#
List the players who are inside a volume.
Asks the server which players are online, then for the position of each. A player whose position can not be read (for example while they respawn) is left out, so this does not raise
PlayerNotInWorldError.Unlike
player_in(), the volume is widened by 2 blocks at each end of its x axis for this test (and not in y or z).
- exception mciwb.PlayerNotInWorldError[source]#
The player (or named entity) could not be found in the world.
Raised by
pos,pos_f,facingandrotationwhen the server has returned no data for the entity in five tries, 0.1 seconds apart. That happens when the player has left the game, and for a while when they respawn or change dimension. AMonitorthat gets this error from one of its functions logs a warning and polls again afterplayer_missing_backoffseconds.
Background threads#
- class mciwb.Monitor(func=None, params=(), once=False, name=None, poll_rate=0.2, start=True)[source]#
A background thread that calls a list of functions again and again.
The thread calls each of its functions in turn, sleeps for poll_rate seconds, and repeats until the monitor is stopped. It is made with
new_thread(), so it has its own connection to the server, and the functions use it without doing anything special: any call that goes throughget_client()orget_world()works. The thread that creates (or starts) the monitor must have a client itself, as the new connection copies its details.An exception in a function does not stop the monitor. The rest of that round is skipped (with no sleep) and the next round starts:
a
PlayerNotInWorldErroris logged as a warning, and the monitor waitsplayer_missing_backoffseconds before the next round, as the player may come backa timeout of the connection is logged as a warning
anything else is logged as an error with its traceback
Only a lost connection to the server (a
BrokenPipeError) stops the monitor.The threads are daemon threads, so they do not keep a script running: a script that only starts monitors exits at once, and must wait for as long as it wants them to run. Call
stop_all()before exiting.- Parameters:
func (Callable[[...], Any] | None) -- A function to call in the monitor’s thread. If None, the monitor starts with no functions: add them with
add_poller_func().params (tuple[Any, ...]) -- The positional arguments to pass to func.
once (bool) -- If True, call the functions once only and then stop. Use this to run one task in the background.
name (str | None) -- The name of the monitor and of its thread. Defaults to
"Monitor0","Monitor1"and so on.poll_rate (float) -- How long to sleep between rounds of calls, in seconds.
start (bool) -- If True, start the thread at once. If False, call
start_poller()to start it.
Example:
from time import sleep from mciwb.imports import Item, Monitor, Vec3, get_world world = get_world() def flash(pos: Vec3) -> None: lit = world.get_block(pos) == Item.GLOWSTONE world.set_block(pos, Item.STONE if lit else Item.GLOWSTONE) Monitor(flash, params=(Vec3(0, 70, 0),), name="flasher", poll_rate=1) sleep(30) Monitor.stop_named("flasher")
- monitors: ClassVar[list[Monitor]] = []#
The monitors of this process whose threads are running (or about to stop). A monitor is added when it starts and taken out when it stops.
- player_missing_backoff = 5.0#
Seconds to wait before polling again after a function raised
PlayerNotInWorldError, which happens while the player respawns, changes dimension or is briefly disconnected.
- pollers: list[tuple[Callable[[...], Any], tuple[Any, ...]]]#
The functions that the thread calls, each with the tuple of arguments to pass to it, in the order they are called. Emptied when the monitor stops.
- name#
The name of the monitor, which is also the name of its thread.
- once#
True if the monitor stops after calling its functions once.
- poll_rate#
Seconds to sleep between rounds of calls. May be changed while the monitor is running.
- start_poller()[source]#
Start the monitor’s thread, which calls the functions repeatedly.
Only needed for a monitor created with
start=False, or to start a monitor again after it has stopped (add its functions again first, as stopping empties the list). Does nothing if the monitor has a thread already.Call this from a thread that has a client, such as the main thread of a script: the new thread connects to the same server.
- add_poller_func(func, params=())[source]#
Add a function to those that the monitor calls.
It is called after the functions already in the list, starting with the next round if the monitor is running.
- remove_poller_func(func)[source]#
Remove a function from those that the monitor calls.
If the function was added more than once, only its first entry is removed. If it is not in the list, an error is logged and nothing else happens.
- classmethod stop_all(timeout=5.0)[source]#
Stop every running monitor and wait for their threads to finish.
Call this before exiting the program so that background work is finished cleanly.
- Parameters:
timeout (float) -- The most seconds to wait for each thread to finish.
- stop()[source]#
Ask this monitor to stop.
This returns at once. The thread finishes the round of calls that it is in (and its sleep), then exits, empties
pollersand takes the monitor out ofmonitors. Calling it from one of the monitor’s own functions is fine. Usestop_all()to wait for threads to finish.
- classmethod stop_named(name)[source]#
Ask every running monitor with the given name to stop.
Like
stop(), this does not wait for the threads to finish, but the monitors are taken out ofmonitorsat once. Does nothing if no running monitor has the name.- Parameters:
name (str) -- The name given to the monitor when it was created.
Switches#
- class mciwb.Switch(position, item, callback, name='')[source]#
A lever, button, pressure plate or tripwire hook that calls a function.
Creating a Switch places the block in the world, replacing whatever is at position, and starts a
Monitorthread that reads the block’spoweredstate about five times a second. Each time the state changes, callback is called in that thread with the Switch as its only argument, andpoweredholds the new state. A lever calls it once for on and once for off. A button or a pressure plate calls it when pressed and again when it springs back.The block is placed with the properties in
item_types: a lever or button always sits on top of the block below it, facing north.- Parameters:
position (Vec3) -- Where to place the switch.
item (Item) -- The kind of switch. Its name must contain one of the keys of
item_types, soItem.LEVER,Item.STONE_BUTTONandItem.OAK_PRESSURE_PLATEare all accepted.callback (Callable[[Switch], None]) -- The function to call, with this Switch, when the state of the switch changes.
name (str) -- A name for the switch and its monitor thread, for
remove_named(). Defaults to"switch"followed byid.
- Raises:
ValueError -- If item is not a supported kind of switch. Nothing is placed in the world.
Example:
from mciwb.imports import Item, Switch, Vec3, get_world world = get_world() def lamp(switch: Switch) -> None: block = Item.GLOWSTONE if switch.powered else Item.STONE world.set_block(switch.pos + Vec3(0, 3, 0), block) Switch(Vec3(10, 64, 10), Item.LEVER, lamp, name="lamp") ... Switch.remove_named("lamp")
- switches: list[Switch] = []#
The switches made by this process that have not been removed, in the order they were made. Switches made by another script, or in an earlier run, are not in it.
- pos#
The position of the switch in the world.
- callback#
The function called with this Switch when its state changes.
- id#
The number of the switch. It is 1 for the first one made by this process, 2 for the next and so on.
- name#
The name of the switch, which is also the name of its monitor.
- powered#
The state of the switch when it was last read. True if it is on (powered), and False until the monitor first sees it on.
- on#
The block state of the switch when on, such as
minecraft:lever[powered=true], forcheck_state().
- off#
The block state of the switch when off, such as
minecraft:lever[powered=false].
- classmethod remove_named(name)[source]#
Remove every switch with the given name from the world.
Does nothing if there is no such switch in
switches.- Parameters:
name (str) -- The name given to the switch when it was made.
- remove()[source]#
Remove the switch from the world and stop watching it.
The switch is taken out of
switches, its monitor is stopped and its block is replaced with air.
- mciwb.switch.item_types = {'BUTTON': '[face=floor, facing=north]', 'LEVER': '[face=floor, facing=north]', 'PRESSURE_PLATE': '[]', 'TRIPWIRE_HOOK': '[]'}#
supported switch types and the properties to set on them
Signs#
- class mciwb.Signs(player)[source]#
Watch for command signs placed by one player, and call a function for each.
A command sign is a sign whose first line of text is the name of a command. When the player places one in front of themselves, the sign is removed and the function registered for its text is called with the position of the block that the sign points at: the block behind a wall sign, or the block below a standing sign.
A new Signs object knows the four signs of its own
CopyPaste(seeget_commands()):select,paste,expandandclear. Add more withadd_sign(). For best results, use the bound methods of an object as the callback functions, so that the object can keep state between signs.Nothing happens until
poll()is called repeatedly, which is a job for aMonitor.add_player()does all of this: it makes the Signs object for the player (world.signsfor the first player), starts a Monitor that polls it and gives the player the signs.- Parameters:
player (Player) -- The player whose signs are watched for.
Example:
from mciwb.imports import Item, Vec3, get_world world = get_world() # connected with a player, see Iwb.add_player def pillar(pos: Vec3) -> None: for height in range(1, 6): world.set_block(pos + Vec3(0, height, 0), Item.QUARTZ_PILLAR) world.signs.add_sign("pillar", pillar) world.signs.give_signs()
- player#
The player whose signs are watched for.
- signs: dict[str, Callable[[Vec3], None]]#
The known command signs. Each sign’s text is mapped to the function that is called, with the position the sign points at, when the player places it.
- poll()[source]#
Look for a sign in front of the player and act on its text.
Call this repeatedly, for example from a
Monitor. Each call reads twelve blocks: those 1, 2 and 3 blocks away from the player in the compass direction that they are facing, from one block below the player’s feet to two blocks above them. For each one that is a sign with text on the first line of its front,do_action()is called.- Raises:
PlayerNotInWorldError -- If the player is not found in the world.
- do_action(command, target, block_pos)[source]#
Call the function registered for the text of a sign.
If command is one of the known signs, the sign is removed from the world (its block is set to air) and the function is called with target. Any other text is taken to be an ordinary sign: it is left alone and nothing is called.
- add_sign(name, function)[source]#
Add a new command sign and the function that it calls.
A sign that is already known by this name is replaced. The player gets the new sign at the next call of
give_signs().
- remove_sign(name)[source]#
Stop responding to the sign with the given name.
Does nothing if there is no such sign. Signs that the player already holds stay in their inventory, as ordinary signs.
- Parameters:
name (str) -- The text of the sign.
- classmethod sign_block(text)[source]#
Make the block string for a standing oak sign with the given text.
For use with the
setblockcommand, for example to place a command sign from code.- Parameters:
text (str) -- The text for the first line of the sign.
- Returns:
The block name with the NBT data that holds the text, such as
minecraft:oak_sign{front_text:{messages:["select","","",""]}}.- Return type:
Example:
from mciwb.imports import Signs, Vec3, get_client get_client().setblock(Vec3(10, 64, 10), Signs.sign_block("select"))
Copy and paste#
- class mciwb.CopyPaste[source]#
Select a box of blocks in the world, then copy, fill or clear it.
A CopyPaste holds two things:
the selection: a box of blocks with opposite corners
start_posandstop_pos. Nothing is read from the world when it is set: the blocks are copied by the server at the time of each paste.the paste point,
paste_pos: where the copy of the start corner last went. Selecting moves it back to the start corner.
Set the selection with two calls of
select()(one for each corner) or withapply_volume(), and change it withexpand()andexpand_to(). Thenpaste()copies it somewhere else, any number of times.fill()andclear()work on the box at the paste point: the selection itself until something is pasted, and the latest pasted copy after that.The other methods fail until a selection has been made.
The
select,paste,expandandclearcommand signs ofSignscall the methods of its CopyPaste, which isworld.copierfor the player added withadd_player().Example:
from mciwb.imports import CopyPaste, Vec3 copier = CopyPaste() copier.select(Vec3(4, 68, 4)) copier.select(Vec3(0, 64, 0)) # the start corner # two copies, each with its copy of the start corner at the point copier.paste(Vec3(10, 64, 0)) copier.paste(Vec3(20, 64, 0)) copier.clear() # removes the second copy
- start_pos: Vec3#
The corner of the selection that was selected last, or None before the first select. Pasting puts the copy of this corner at the paste point.
- stop_pos: Vec3#
The opposite corner of the selection. It is the point selected before
start_pos, or None before the first select.
- paste_pos: Vec3#
The paste point. It is where the last paste put the copy of the start corner, or the start corner itself since the last select. None before the first select.
- size#
The vector from the start corner to the stop corner of the selection. Each part is one less than the number of blocks along that axis, and is negative where the stop corner is the lower.
- apply_volume(vol)[source]#
Set the selection from a volume.
The start corner of the selection, and the paste point, are set to the start of the volume (its lowest corner), and the stop corner to its end.
- Parameters:
vol (Volume) -- The volume to select.
- get_commands()[source]#
Get the command signs for copy and paste, with the method for each.
Signsuses this for its first set of signs.- Returns:
A dictionary of sign text to the method that the sign calls with the position it points at:
"select"toselect(),"paste"topaste(),"expand"toexpand_to()and"clear"toclear().
- select(pos)[source]#
Select a corner of the box of blocks to copy.
pos becomes the start corner, and the previous start corner becomes the stop corner, so the selection is always the box between the last two points selected. After the first call it is the single block at pos. The paste point moves to pos as well.
- Parameters:
pos (Vec3) -- The new start corner. Its coordinates are rounded down to whole numbers for the start corner. On the first call the stop corner is pos as it was given, not rounded, so pass whole numbers to select exactly one block.
- paste(pos, force=True)[source]#
Copy the blocks of the selection to another place.
The copy is placed so that the copy of the start corner (the corner selected last) is at pos, and it extends from there in the same directions as the selection does. Every block is copied, air included, with the
clonecommand. pos becomes the paste point. The server’s reply is logged.- Parameters:
pos (Vec3) -- Where to put the copy of the start corner.
force -- If True (the default), the copy may overlap the selection. If False, the server refuses to make a copy that would overlap.
- paste_safe(pos)[source]#
Copy the blocks of the selection, unless the copy would overlap it.
The same as
paste()withforce=False: the server refuses to make a copy that overlaps the selection. The paste point still moves to pos.- Parameters:
pos (Vec3) -- Where to put the copy of the start corner.
- fill(pos=zero, item=Item.AIR)[source]#
Fill the box at the paste point with one kind of block.
The box has the size of the selection and its start corner at the paste point. So after a paste it is the copy just made, and after a select (with no paste since) it is the selection itself. The server’s reply is logged.
- clear(_=zero)[source]#
Clear the box at the paste point, by filling it with air.
This is
fill()with its defaults. After a paste it removes the copy just made, not the selection. After a select (with no paste since) it empties the selection itself.- Parameters:
_ (Vec3) -- Ignored. It is there so that this method can be the callback of the
clearcommand sign, which is called with a position.
- expand_to(pos)[source]#
Grow the selection so that it includes a point.
On each axis where pos is outside the selection, the nearer face of the selection moves outwards to pos. The selection never shrinks. The paste point moves back to the start corner.
- Parameters:
pos (Vec3) -- The point to include in the selection.
- expand(x=0, y=0, z=0)[source]#
Grow the selection by a number of blocks along each axis.
The sign of each argument chooses the face that moves: a positive number moves the face at the higher coordinate that many blocks further up the axis, and a negative number moves the face at the lower coordinate that many blocks further down it. The paste point moves back to the start corner.
- Parameters:
x -- Blocks to grow by along x: positive to the east, negative to the west.
y -- Blocks to grow by along y: positive upwards, negative downwards.
z -- Blocks to grow by along z: positive to the south, negative to the north.
Example:
copier.expand(y=3) # three blocks taller copier.expand(x=-2) # two blocks further west
Walls#
- class mciwb.Wall(height=None, item=Item.STONE, profile=None)[source]#
Draw walls between pairs of points in the world.
A wall is drawn column by column along the line from its start to its end. The profile describes the columns, and is repeated along the length of the wall:
the profile is a list of columns
each column is a list of blocks, from the top of the column down
each block is an
Item(or a block string), or a list of them to make the wall more than one block thick (extending to the right of the direction of drawing)
If the column is shorter than height it is repeated to fill the height.
A wall follows the longer of the x and z distances between its two ends, and steps sideways one block at a time to cover the shorter one, so a diagonal wall is a staircase in plan. The whole wall is drawn at the height of its end point. Blocks are placed one at a time through the client of the calling thread, replacing what is there.
- Parameters:
- Raises:
ValueError -- If neither height nor profile is given.
Example:
from mciwb.imports import Item, Vec3, Wall # a castle wall with crenellations on top battlement = [Item.AIR, Item.STONE_BRICKS, Item.STONE_BRICKS] solid = [Item.STONE_BRICKS] * 3 wall = Wall(profile=[solid, battlement]) wall.set_start(Vec3(0, 63, 0)) wall.draw(Vec3(20, 63, 0)) wall.draw(Vec3(20, 63, 20)) # carries on from the first wall
- height: int | None#
The height of the wall in blocks, or None to use the length of each column of the profile.
- profile#
The list of columns that is repeated along the wall.
- profile_idx#
The index in
profileof the next column to draw. It is not reset between walls, so the pattern carries on round the corners of a connected series of walls.
- profile_idx_limit#
The number of columns in the profile.
- set_start(pos)[source]#
Set the start point of the next wall.
The wall is built on top of the block at pos.
- Parameters:
pos (Vec3) -- The block that the wall starts on.
- set_end(pos)[source]#
Set the end point of the next wall without drawing it.
A later call of
draw()with no argument draws the wall to this point.- Parameters:
pos (Vec3) -- The block that the wall ends on.
- draw(end=None)[source]#
Draw the wall from the start point to an end point.
The end becomes the start of the next wall, so calling draw repeatedly draws a connected series of walls. The wall is level: all of it stands at the height of the end point, whatever the height of the start point was.
- Parameters:
end (Vec3 | None) -- The block that the wall ends on. If None, the end point set with
set_end()is used.- Raises:
ValueError -- If no start point has been set, if there is no end point, or if the end is directly above or below the start (a wall with no length).
- class mciwb.WallMaker(wall=None)[source]#
Build walls interactively with command signs.
Creating a WallMaker adds a
start_wallsign and anend_wallsign to theSignsof the world’s player, and gives the signs to the player. Placestart_wallto set the start of a wall, then placeend_wallto draw the wall up to it. Keep placingend_wallsigns to draw a connected series of walls.Requires a world with a player, added with
add_player(): without one, creating a WallMaker fails with anAttributeError.Example:
from mciwb.imports import Item, Wall, WallMaker maker = WallMaker(Wall(height=5, item=Item.BRICKS)) ... maker.remove()
- start = 'start_wall'#
The text of the sign that sets the start of a wall.
- end = 'end_wall'#
The text of the sign that draws the wall to where it is placed.
NBT text#
- mciwb.parse_nbt(s_nbt_text)[source]#
Convert SNBT text, such as the reply to
data get, to Python objects.SNBT is the text form of Minecraft’s NBT data: see https://minecraft.wiki/w/NBT_format. Any text before the first
[or{is dropped, so the whole reply to adata getcommand can be passed in. Compounds become dictionaries, and lists and typed arrays become lists.This is a simple conversion made with regular expressions and
json.loads(), not a full SNBT parser. It only goes one way, since these details are lost:the difference between byte, short, int and long (the suffixes
b,s, none andl): all becomeintthe difference between float and double (the suffixes
fandd): both becomefloatthe difference between SNBT and raw JSON held in a single quoted string: the JSON is parsed into objects too
And some values are left as strings:
trueandfalsebecome the strings"True"and"False"negative whole numbers, as in
"-5"or"-1b"numbers with a decimal point and no
fordsuffix, as in"1.5"numbers with an upper case suffix or an exponent, as in
"10L"
- Parameters:
s_nbt_text (str) -- The SNBT text, with or without the words that the server puts before it.
- Returns:
The data as dictionaries, lists, strings, ints and floats. If the text can not be converted (for example an error message from the server with no data in it), an error is logged and the result is None: no exception is raised.
- Return type:
>>> from mciwb.nbt import parse_nbt >>> parse_nbt('Steve has the following entity data: [0.5d, 64.0d, -3.5d]') [0.5, 64.0, -3.5] >>> parse_nbt('{Slot: 0b, id: "minecraft:oak_sign", count: 16}') {'Slot': 0, 'id': 'minecraft:oak_sign', 'count': 16}