tcod.console

libtcod works with a special ‘root’ console. You create this console using the tcod.console_init_root function. Usually after setting the font with console_set_custom_font first.

Example:

# Make sure 'arial10x10.png' is in the same directory as this script.
import time

import tcod

# Setup the font.
tcod.console_set_custom_font(
    'arial10x10.png',
    tcod.FONT_LAYOUT_ASCII_INROW | tcod.FONT_LAYOUT_TCOD,
    )
# Initialize the root console in a context.
with tcod.console_init_root(80, 60, 'title') as root_console:
    root_console.print_(x=0, y=0, string='Hello World!')
    tcod.console_flush() # Show the console.
    time.sleep(3) # Wait 3 seconds.
# The window is closed here, after the above context exits.
class tcod.console.Console(width, height)[source]
Parameters:
  • width (int) – Width of the new Console.
  • height (int) – Height of the new Console.
console_c

CData – A cffi pointer to a TCOD_console_t object.

__bool__()[source]

Returns False if this is the root console.

This mimics libtcodpy behavior.

__enter__()[source]

Returns this console in a managed context.

When the root console is used as a context, the graphical window will close once the context is left as if tcod.console_delete was called on it.

This is useful for some Python IDE’s like IDLE, where the window would not be closed on its own otherwise.

__exit__(*args)[source]

Closes the graphical window on exit.

Some tcod functions may have undefined behavior after this point.

__nonzero__()

Returns False if this is the root console.

This mimics libtcodpy behavior.

blit(dest, dest_x=0, dest_y=0, src_x=0, src_y=0, width=0, height=0, fg_alpha=1.0, bg_alpha=1.0, key_color=None)[source]

Blit from this console onto the dest console.

Parameters:
  • dest (Console) – The destintaion console to blit onto.
  • dest_x (int) – Leftmost coordinate of the destintaion console.
  • dest_y (int) – Topmost coordinate of the destintaion console.
  • src_x (int) – X coordinate from this console to blit, from the left.
  • src_y (int) – Y coordinate from this console to blit, from the top.
  • width (int) –

    The width of the region to blit.

    If this is 0 the maximum possible width will be used.

  • height (int) –

    The height of the region to blit.

    If this is 0 the maximum possible height will be used.

  • fg_alpha (float) – Foreground color alpha vaule.
  • bg_alpha (float) – Background color alpha vaule.
  • key_color (Optional[Tuple[int, int, int]]) – None, or a (red, green, blue) tuple with values of 0-255.

Changed in version 4.0: Parameters were rearraged and made optional.

Previously they were: (x, y, width, height, dest, dest_x, dest_y, *)

clear()[source]

Reset this console to its default colors and the space character.

get_height_rect(x, y, width, height, string)[source]

Return the height of this text word-wrapped into this rectangle.

Parameters:
  • x (int) – The x coordinate from the left.
  • y (int) – The y coordinate from the top.
  • width (int) – Maximum width to render the text.
  • height (int) – Maximum lines to render the text.
  • string (Text) – A Unicode string.
Returns:

The number of lines of text once word-wrapped.

Return type:

int

hline(x, y, width, bg_blend=13)[source]

Draw a horizontal line on the console.

This always uses the character 196, the horizontal line character.

Parameters:
  • x (int) – The x coordinate from the left.
  • y (int) – The y coordinate from the top.
  • width (int) – The horozontal length of this line.
  • bg_blend (int) – The background blending flag.
print_(x, y, string, bg_blend=13, alignment=None)[source]

Print a color formatted string on a console.

Parameters:
  • x (int) – The x coordinate from the left.
  • y (int) – The y coordinate from the top.
  • string (Text) – A Unicode string optionaly using color codes.
  • bg_blend (int) – Blending mode to use, defaults to BKGND_DEFAULT.
  • alignment (Optinal[int]) – Text alignment.
print_frame(x, y, width, height, string='', clear=True, bg_blend=13)[source]

Draw a framed rectangle with optinal text.

This uses the default background color and blend mode to fill the rectangle and the default foreground to draw the outline.

string will be printed on the inside of the rectangle, word-wrapped.

Parameters:
  • x (int) – The x coordinate from the left.
  • y (int) – The y coordinate from the top.
  • width (int) – The width if the frame.
  • height (int) – The height of the frame.
  • string (Text) – A Unicode string to print.
  • clear (bool) – If True all text in the affected area will be removed.
  • bg_blend (int) – The background blending flag.

Note

This method does not support Unicode outside of the 0-255 range.

print_rect(x, y, width, height, string, bg_blend=13, alignment=None)[source]

Print a string constrained to a rectangle.

If h > 0 and the bottom of the rectangle is reached, the string is truncated. If h = 0, the string is only truncated if it reaches the bottom of the console.

Parameters:
  • x (int) – The x coordinate from the left.
  • y (int) – The y coordinate from the top.
  • width (int) – Maximum width to render the text.
  • height (int) – Maximum lines to render the text.
  • string (Text) – A Unicode string.
  • bg_blend (int) – Background blending flag.
  • alignment (Optional[int]) – Alignment flag.
Returns:

The number of lines of text once word-wrapped.

Return type:

int

put_char(x, y, ch, bg_blend=13)[source]

Draw the character c at x,y using the default colors and a blend mode.

Parameters:
  • x (int) – The x coordinate from the left.
  • y (int) – The y coordinate from the top.
  • ch (int) – Character code to draw. Must be in integer form.
  • bg_blend (int) – Blending mode to use, defaults to BKGND_DEFAULT.
rect(x, y, width, height, clear, bg_blend=13)[source]

Draw a the background color on a rect optionally clearing the text.

If clr is True the affected tiles are changed to space character.

Parameters:
  • x (int) – The x coordinate from the left.
  • y (int) – The y coordinate from the top.
  • width (int) – Maximum width to render the text.
  • height (int) – Maximum lines to render the text.
  • clear (bool) – If True all text in the affected area will be removed.
  • bg_blend (int) – Background blending flag.
set_key_color(color)[source]

Set a consoles blit transparent color.

Parameters:color (Tuple[int, int, int]) –
vline(x, y, height, bg_blend=13)[source]

Draw a vertical line on the console.

This always uses the character 179, the vertical line character.

Parameters:
  • x (int) – The x coordinate from the left.
  • y (int) – The y coordinate from the top.
  • height (int) – The horozontal length of this line.
  • bg_blend (int) – The background blending flag.
bg

A uint8 array with the shape (height, width, 3).

You can change the consoles background colors by using this array.

Index this array with console.bg[y, x, channel]

ch

An integer array with the shape (height, width).

You can change the consoles character codes by using this array.

Index this array with console.ch[y, x]

default_alignment

int – The default text alignment.

default_bg

Tuple[int, int, int] – The default background color.

default_bg_blend

int – The default blending mode.

default_fg

Tuple[int, int, int] – The default foreground color.

fg

A uint8 array with the shape (height, width, 3).

You can change the consoles foreground colors by using this array.

Index this array with console.fg[y, x, channel]

height

int – The height of this Console. (read-only)

width

int – The width of this Console. (read-only)

tcod.map

libtcod map attributes and field-of-view functions.

Example:

>>> import tcod.map
>>> m = tcod.map.Map(width=3, height=4)
>>> m.walkable
array([[False, False, False],
       [False, False, False],
       [False, False, False],
       [False, False, False]], dtype=bool)

# Like the rest of the tcod modules, all arrays here are
# in row-major order and are addressed with [y,x]
>>> m.transparent[:] = True # Sets all to True.
>>> m.transparent[1:3,0] = False # Sets (1, 0) and (2, 0) to False.
>>> m.transparent
array([[ True,  True,  True],
       [False,  True,  True],
       [False,  True,  True],
       [ True,  True,  True]], dtype=bool)

>>> m.compute_fov(0, 0)
>>> m.fov
array([[ True,  True,  True],
       [ True,  True,  True],
       [False,  True,  True],
       [False, False,  True]], dtype=bool)
>>> m.fov[3,1]
False
class tcod.map.Map(width, height)[source]

A map containing libtcod attributes.

Changed in version 4.1: transparent, walkable, and fov are now numpy boolean arrays.

Parameters:
  • width (int) – Width of the new Map.
  • height (int) – Height of the new Map.
width

int – Read only width of this Map.

height

int – Read only height of this Map.

transparent

A boolean array of transparent cells.

walkable

A boolean array of walkable cells.

fov

A boolean array of the cells lit by :any:’compute_fov’.

compute_fov(x, y, radius=0, light_walls=True, algorithm=12)[source]

Compute a field-of-view on the current instance.

Parameters:
  • x (int) – Point of view, x-coordinate.
  • y (int) – Point of view, y-coordinate.
  • radius (int) –

    Maximum view distance from the point of view.

    A value of 0 will give an infinite distance.

  • light_walls (bool) – Light up walls, or only the floor.
  • algorithm (int) – Defaults to tcod.FOV_RESTRICTIVE

tcod.bsp

The following example shows how to travrse the BSP tree using Python. This assumes create_room and connect_rooms will be replaced by custom code.

Example:

import tcod.bsp

def create_room(node):
    """Initialize the room at this current node."""
    print('Create a room for %s.' % node)

def connect_rooms(node):
    """Connect two fully initialized rooms."""
    node1, node2 = node.children
    print('Connect the rooms:\n%s\n%s' % (node1, node2))

def traverse(node):
    """Traverse a BSP tree dispatching nodes to the correct calls."""
    # For nodes without children, node.children is an empty tuple.
    for child in node.children:
        traverse(child)

    if node.children:
        connect_rooms(node)
    else:
        create_room(node)

bsp = tcod.bsp.BSP(x=0, y=0, width=80, height=60)
bsp.split_recursive(
    depth=5,
    min_width=3,
    min_height=3,
    max_horizontal_ratio=1.5,
    max_vertical_ratio=1.5,
    )
traverse(bsp)
class tcod.bsp.BSP(x, y, width, height)[source]

A binary space partitioning tree which can be used for simple dungeon generation.

x

int – Rectangle left coordinate.

y

int – Rectangle top coordinate.

width

int – Rectangle width.

height

int – Rectangle height.

level

int – This nodes depth.

position

int – The integer of where the node was split.

horizontal

bool – This nodes split orientation.

parent

Optional[BSP] – This nodes parent or None

children

Optional[Tuple[BSP, BSP]] – A tuple of (left, right) BSP instances, or None if this BSP has no children.

Parameters:
  • x (int) – Rectangle left coordinate.
  • y (int) – Rectangle top coordinate.
  • width (int) – Rectangle width.
  • height (int) – Rectangle height.
__str__()[source]

Provide a useful readout when printed.

contains(x, y)[source]

Returns True if this node contains these coordinates.

Parameters:
  • x (int) – X position to check.
  • y (int) – Y position to check.
Returns:

True if this node contains these coordinates.

Otherwise False.

Return type:

bool

find_node(x, y)[source]

Return the deepest node which contains these coordinates.

Returns:BSP object or None.
Return type:Optional[BSP]
split_once(horizontal, position)[source]

Split this partition into 2 sub-partitions.

Parameters:
  • horizontal (bool) –
  • position (int) –
split_recursive(depth, min_width, min_height, max_horizontal_ratio, max_vertical_ratio, seed=None)[source]

Divide this partition recursively.

Parameters:
  • depth (int) – The maximum depth to divide this object recursively.
  • min_width (int) – The minimum width of any individual partition.
  • min_height (int) – The minimum height of any individual partition.
  • max_horizontal_ratio (float) – Prevent creating a horizontal ratio more extreme than this.
  • max_vertical_ratio (float) – Prevent creating a vertical ratio more extreme than this.
  • seed (Optional[tcod.random.Random]) – The random number generator to use.
walk()[source]

Iterate over this BSP’s hieracrhy.

The iterator will include the instance which called it. It will traverse its own children and grandchildren, in no particular order.

Returns:An iterator of BSP nodes.
Return type:Iterator[BSP]

Deprecated since version 2.3: See the module example for how to iterate over a BSP tree.

tcod.path

Example:

>>> import numpy as np
>>> import tcod.path
>>> dungeon = np.array(
...     [
...         [1, 0, 1, 1, 1],
...         [1, 0, 1, 0, 1],
...         [1, 1, 1, 0, 1],
...     ],
...     dtype=np.int8,
...     )
...
>>> height, width = dungeon.shape

# Create a pathfinder from a numpy array.
# This is the recommended way to use the tcod.path module.
>>> astar = tcod.path.AStar(dungeon)
>>> print(astar.get_path(0, 0, 4, 2))
[(0, 1), (1, 2), (2, 1), (3, 0), (4, 1), (4, 2)]
>>> astar.cost[0, 1] = 1 # You can access the map array via this attribute.
>>> print(astar.get_path(0, 0, 4, 2))
[(1, 0), (2, 0), (3, 0), (4, 1), (4, 2)]

# Create a pathfinder from an edge_cost function.
# Calling Python functions from C is known to be very slow.
>>> def edge_cost(my_x, my_y, dest_x, dest_y):
...     return dungeon[dest_y, dest_x]
...
>>> dijkstra = tcod.path.Dijkstra(
...     tcod.path.EdgeCostCallback(edge_cost, width, height),
...     )
...
>>> dijkstra.set_goal(0, 0)
>>> print(dijkstra.get_path(4, 2))
[(1, 0), (2, 0), (3, 0), (4, 1), (4, 2)]
class tcod.path.AStar(cost, diagonal=1.41)[source]
Parameters:
  • cost (Union[tcod.map.Map, numpy.ndarray, Any]) –
  • diagonal (float) – Multiplier for diagonal movement. A value of 0 will disable diagonal movement entirely.
get_path(start_x, start_y, goal_x, goal_y)[source]

Return a list of (x, y) steps to reach the goal point, if possible.

Parameters:
  • start_x (int) – Starting X position.
  • start_y (int) – Starting Y position.
  • goal_x (int) – Destination X position.
  • goal_y (int) – Destination Y position.
Returns:

A list of points, or an empty list if there is no valid path.

Return type:

List[Tuple[int, int]]

class tcod.path.Dijkstra(cost, diagonal=1.41)[source]
Parameters:
  • cost (Union[tcod.map.Map, numpy.ndarray, Any]) –
  • diagonal (float) – Multiplier for diagonal movement. A value of 0 will disable diagonal movement entirely.
get_path(x, y)[source]

Return a list of (x, y) steps to reach the goal point, if possible.

set_goal(x, y)[source]

Set the goal point and recompute the Dijkstra path-finder.

class tcod.path.EdgeCostCallback(callback, width, height)[source]

Calculate cost from an edge-cost callback.

Parameters:
  • callback (Callable[[int, int, int, int], float]) – A callback which can handle the following parameters: (source_x:int, source_y:int, dest_x:int, dest_y:int) -> float
  • width (int) – The maximum width of this callback.
  • height (int) – The maximum height of this callback.
class tcod.path.NodeCostArray[source]

Calculate cost from a numpy array of nodes.

Parameters:array (numpy.ndarray) – A numpy array with the cost of each node.

tcod.image

class tcod.image.Image(width, height)[source]
Parameters:
  • width (int) – Width of the new Image.
  • height (int) – Height of the new Image.
width

int – Read only width of this Image.

height

int – Read only height of this Image.

blit(console, x, y, bg_blend, scale_x, scale_y, angle)[source]

Blit onto a Console using scaling and rotation.

Parameters:
  • console (Console) – Blit destination Console.
  • x (int) – Console X position for the center of the Image blit.
  • y (int) – Console Y position for the center of the Image blit. The Image blit is centered on this position.
  • bg_blend (int) – Background blending mode to use.
  • scale_x (float) – Scaling along Image x axis. Set to 1 for no scaling. Must be over 0.
  • scale_y (float) – Scaling along Image y axis. Set to 1 for no scaling. Must be over 0.
  • angle (float) – Rotation angle in radians. (Clockwise?)
blit_2x(console, dest_x, dest_y, img_x=0, img_y=0, img_width=-1, img_height=-1)[source]

Blit onto a Console with double resolution.

Parameters:
  • console (Console) – Blit destination Console.
  • dest_x (int) – Console tile X position starting from the left at 0.
  • dest_y (int) – Console tile Y position starting from the top at 0.
  • img_x (int) – Left corner pixel of the Image to blit
  • img_y (int) – Top corner pixel of the Image to blit
  • img_width (int) – Width of the Image to blit. Use -1 for the full Image width.
  • img_height (int) – Height of the Image to blit. Use -1 for the full Image height.
blit_rect(console, x, y, width, height, bg_blend)[source]

Blit onto a Console without scaling or rotation.

Parameters:
  • console (Console) – Blit destination Console.
  • x (int) – Console tile X position starting from the left at 0.
  • y (int) – Console tile Y position starting from the top at 0.
  • width (int) – Use -1 for Image width.
  • height (int) – Use -1 for Image height.
  • bg_blend (int) – Background blending mode to use.
clear(color)[source]

Fill this entire Image with color.

Parameters:color (Union[Tuple[int, int, int], Sequence[int]]) – An (r, g, b) sequence or Color instance.
get_alpha(x, y)[source]

Get the Image alpha of the pixel at x, y.

Parameters:
  • x (int) – X pixel of the image. Starting from the left at 0.
  • y (int) – Y pixel of the image. Starting from the top at 0.
Returns:

The alpha value of the pixel. With 0 being fully transparent and 255 being fully opaque.

Return type:

int

get_mipmap_pixel(left, top, right, bottom)[source]

Get the average color of a rectangle in this Image.

Parameters should stay within the following limits: * 0 <= left < right < Image.width * 0 <= top < bottom < Image.height

Parameters:
  • left (int) – Left corner of the region.
  • top (int) – Top corner of the region.
  • right (int) – Right corner of the region.
  • bottom (int) – Bottom corner of the region.
Returns:

An (r, g, b) tuple containing the averaged color value. Values are in a 0 to 255 range.

Return type:

Tuple[int, int, int]

get_pixel(x, y)[source]

Get the color of a pixel in this Image.

Parameters:
  • x (int) – X pixel of the Image. Starting from the left at 0.
  • y (int) – Y pixel of the Image. Starting from the top at 0.
Returns:

An (r, g, b) tuple containing the pixels color value. Values are in a 0 to 255 range.

Return type:

Tuple[int, int, int]

hflip()[source]

Horizontally flip this Image.

invert()[source]

Invert all colors in this Image.

put_pixel(x, y, color)[source]

Change a pixel on this Image.

Parameters:
  • x (int) – X pixel of the Image. Starting from the left at 0.
  • y (int) – Y pixel of the Image. Starting from the top at 0.
  • color (Union[Tuple[int, int, int], Sequence[int]]) – An (r, g, b) sequence or Color instance.
refresh_console(console)[source]

Update an Image created with tcod.image_from_console.

The console used with this function should have the same width and height as the Console given to tcod.image_from_console. The font width and height must also be the same as when tcod.image_from_console was called.

Parameters:console (Console) – A Console with a pixel width and height matching this Image.
rotate90(rotations=1)[source]

Rotate this Image clockwise in 90 degree steps.

Parameters:rotations (int) – Number of 90 degree clockwise rotations.
save_as(filename)[source]

Save the Image to a 32-bit .bmp or .png file.

Parameters:filename (Text) – File path to same this Image.
scale(width, height)[source]

Scale this Image to the new width and height.

Parameters:
  • width (int) – The new width of the Image after scaling.
  • height (int) – The new height of the Image after scaling.
set_key_color(color)[source]

Set a color to be transparent during blitting functions.

Parameters:color (Union[Tuple[int, int, int], Sequence[int]]) – An (r, g, b) sequence or Color instance.
vflip()[source]

Vertically flip this Image.

tcod.random

Random module docs.

class tcod.random.Random(algorithm, seed=None)[source]

The libtcod random number generator.

If all you need is a random number generator then it’s recommended that you use the random module from the Python standard library.

If seed is None then a random seed will be generated.

Parameters:
  • algorithm (int) – The algorithm to use.
  • seed (Optional[Hashable]) – Could be a 32-bit integer, but any hashable object is accepted.
random_c

CData – A cffi pointer to a TCOD_random_t object.

__getstate__()[source]

Pack the self.random_c attribute into a portable state.

__setstate__(state)[source]

Create a new cdata object with the stored paramaters.

guass(mu, sigma)[source]

Return a random number using Gaussian distribution.

Parameters:
  • mu (float) – The median returned value.
  • sigma (float) – The standard deviation.
Returns:

A random float.

Return type:

float

inverse_guass(mu, sigma)[source]

Return a random Gaussian number using the Box-Muller transform.

Parameters:
  • mu (float) – The median returned value.
  • sigma (float) – The standard deviation.
Returns:

A random float.

Return type:

float

randint(low, high)[source]

Return a random integer within the linear range: low <= n <= high.

Parameters:
  • low (int) – The lower bound of the random range.
  • high (int) – The upper bound of the random range.
Returns:

A random integer.

Return type:

int

uniform(low, high)[source]

Return a random floating number in the range: low <= n <= high.

Parameters:
  • low (int) – The lower bound of the random range.
  • high (int) – The upper bound of the random range.
Returns:

A random float.

Return type:

float

tcod.noise

The Noise.sample_mgrid and Noise.sample_ogrid methods are multi-threaded operations when the Python runtime supports OpenMP. Even when single threaded these methods will perform much better than multiple calls to Noise.get_point.

Example:

import numpy as np
import tcod
import tcod.noise

noise = tcod.noise.Noise(
    dimensions=2,
    algorithm=tcod.NOISE_SIMPLEX,
    implementation=tcod.noise.TURBULENCE,
    hurst=0.5,
    lacunarity=2.0,
    octaves=4,
    seed=None,
    )

# Create a 5x5 open multi-dimensional mesh-grid.
ogrid = [np.arange(5, dtype=np.float32),
         np.arange(5, dtype=np.float32)]
print(ogrid)

# Scale the grid.
ogrid[0] *= 0.25
ogrid[1] *= 0.25

# Return the sampled noise from this grid of points.
samples = noise.sample_ogrid(ogrid)
print(samples)
class tcod.noise.Noise(dimensions, algorithm=2, implementation=0, hurst=0.5, lacunarity=2.0, octaves=4, seed=None)[source]

The hurst exponent describes the raggedness of the resultant noise, with a higher value leading to a smoother noise. Not used with tcod.noise.SIMPLE.

lacunarity is a multiplier that determines how fast the noise frequency increases for each successive octave. Not used with tcod.noise.SIMPLE.

Parameters:
  • dimensions (int) – Must be from 1 to 4.
  • algorithm (int) – Defaults to NOISE_SIMPLEX
  • implementation (int) – Defaults to tcod.noise.SIMPLE
  • hurst (float) – The hurst exponent. Should be in the 0.0-1.0 range.
  • lacunarity (float) – The noise lacunarity.
  • octaves (float) – The level of detail on fBm and turbulence implementations.
  • seed (Optional[Random]) – A Random instance, or None.
noise_c

CData – A cffi pointer to a TCOD_noise_t object.

get_point(x=0, y=0, z=0, w=0)[source]

Return the noise value at the (x, y, z, w) point.

Parameters:
  • x (float) – The position on the 1st axis.
  • y (float) – The position on the 2nd axis.
  • z (float) – The position on the 3rd axis.
  • w (float) – The position on the 4th axis.
sample_mgrid(mgrid)[source]

Sample a mesh-grid array and return the result.

The sample_ogrid method performs better as there is a lot of overhead when working with large mesh-grids.

Parameters:mgrid (numpy.ndarray) – A mesh-grid array of points to sample. A contiguous array of type numpy.float32 is preferred.
Returns:An array of sampled points.
This array has the shape: mgrid.shape[:-1]. The dtype is numpy.float32.
Return type:numpy.ndarray
sample_ogrid(ogrid)[source]

Sample an open mesh-grid array and return the result.

Args
ogrid (Sequence[Sequence[float]]): An open mesh-grid.
Returns:An array of sampled points.
The shape is based on the lengths of the open mesh-grid arrays. The dtype is numpy.float32.
Return type:numpy.ndarray