Tile Drawing/Printing tcod.console#

Libtcod tile-based Consoles and printing functions.

Libtcod consoles are a strictly tile-based representation of colored glyphs/tiles. To render a console you need a tileset and a window to render to. See Getting Started for info on how to set those up.

class tcod.console.Console(width: int, height: int, order: Literal['C', 'F'] = 'C', buffer: NDArray[Any] | None = None)[source]#

A console object containing a grid of characters with foreground/background colors.

width and height are the size of the console (in tiles.)

order determines how the axes of NumPy array attributes are arranged. With the default setting of “C” you use [y, x] to index a consoles arrays such as Console.rgb. order=”F” will swap the first two axes which allows for more intuitive [x, y] indexing. To be consistent you may have to do this for every NumPy array to create.

With buffer the console can be initialized from another array. The buffer should be compatible with the width, height, and order given; and should also have a dtype compatible with Console.DTYPE.

Changed in version 4.3: Added order parameter.

Changed in version 8.5: Added buffer, copy, and default parameters. Arrays are initialized as if the clear method was called.

Changed in version 10.0: DTYPE changed, buffer now requires colors with an alpha channel.

console_c#

A python-cffi “TCOD_Console*” object.

DTYPE#

A class attribute which provides a dtype compatible with this class.

[("ch", np.intc), ("fg", "(4,)u1"), ("bg", "(4,)u1")]

Example:

>>> buffer = np.zeros(
...     shape=(20, 3),
...     dtype=tcod.console.Console.DTYPE,
...     order="F",
... )
>>> buffer["ch"] = ord('_')
>>> buffer["ch"][:, 1] = ord('x')
>>> c = tcod.console.Console(20, 3, order="F", buffer=buffer)
>>> print(c)
<____________________
 xxxxxxxxxxxxxxxxxxxx
 ____________________>

New in version 8.5.

Changed in version 10.0: Added an alpha channel to the color types.

__bool__() bool[source]#

Return False if this is the root console.

This mimics libtcodpy behavior.

__enter__() Console[source]#

Return 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 libtcodpy.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__(*_: object) None[source]#

Close the graphical window on exit.

Some tcod functions may have undefined behavior after this point.

__repr__() str[source]#

Return a string representation of this console.

__str__() str[source]#

Return a simplified representation of this consoles contents.

blit(dest: Console, dest_x: int = 0, dest_y: int = 0, src_x: int = 0, src_y: int = 0, width: int = 0, height: int = 0, fg_alpha: float = 1.0, bg_alpha: float = 1.0, key_color: tuple[int, int, int] | None = None) None[source]#

Blit from this console onto the dest console.

Parameters:
  • dest (Console) – The destination console to blit onto.

  • dest_x (int) – Leftmost coordinate of the destination console.

  • dest_y (int) – Topmost coordinate of the destination 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 value.

  • bg_alpha (float) – Background color alpha value.

  • 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 rearranged and made optional.

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

Changed in version 11.6: Now supports per-cell alpha transparency.

Use Console.buffer to set tile alpha before blit.

clear(ch: int = 32, fg: tuple[int, int, int] = Ellipsis, bg: tuple[int, int, int] = Ellipsis) None[source]#

Reset all values in this console to a single value.

ch is the character to clear the console with. Defaults to the space character.

fg and bg are the colors to clear the console with. Defaults to white-on-black if the console defaults are untouched.

Note

If fg/bg are not set, they will default to default_fg/default_bg. However, default values other than white-on-back are deprecated.

Changed in version 8.5: Added the ch, fg, and bg parameters. Non-white-on-black default values are deprecated.

close() None[source]#

Close the active window managed by libtcod.

This must only be called on the root console, which is returned from libtcodpy.console_init_root.

New in version 11.11.

draw_frame(x: int, y: int, width: int, height: int, title: str = '', clear: bool = True, fg: tuple[int, int, int] | None = None, bg: tuple[int, int, int] | None = None, bg_blend: int = 1, *, decoration: str | tuple[int, int, int, int, int, int, int, int, int] = '┌─┐│ │└─┘') None[source]#

Draw a framed rectangle with an optional title.

x and y are the starting tile, with 0,0 as the upper-left corner of the console.

width and height determine the size of the frame.

title is a Unicode string. The title is drawn with bg as the text color and fg as the background. Using the title parameter is discouraged since the style it uses is hard-coded into libtcod. You should print over the top or bottom border with Console.print_box using your own style.

If clear is True than the region inside of the frame will be cleared.

fg and bg are the foreground and background colors for the frame border. This is a 3-item tuple with (r, g, b) color values from 0 to 255. These parameters can also be set to None to leave the colors unchanged.

bg_blend is the blend type used by libtcod.

decoration is a sequence of glyphs to use for rendering the borders. This a str or tuple of int’s with 9 items with the items arranged in row-major order. If a decoration is given then title can not be used because the style for title is hard-coded. You can easily print along the upper or lower border of the frame manually.

New in version 8.5.

Changed in version 9.0: fg and bg now default to None instead of white-on-black.

Changed in version 12.6: Added decoration parameter.

Changed in version 13.0: x and y are now always used as an absolute position for negative values.

Example:

>>> console = tcod.console.Console(12, 6)
>>> console.draw_frame(x=0, y=0, width=3, height=3)
>>> console.draw_frame(x=3, y=0, width=3, height=3, decoration="╔═╗║ ║╚═╝")
>>> console.draw_frame(x=6, y=0, width=3, height=3, decoration="123456789")
>>> console.draw_frame(x=9, y=0, width=3, height=3, decoration="/-\\| |\\-/")
>>> console.draw_frame(x=0, y=3, width=12, height=3)
>>> console.print_box(x=0, y=3, width=12, height=1, string=" Title ", alignment=tcod.CENTER)
1
>>> console.print_box(x=0, y=5, width=12, height=1, string="┤Lower├", alignment=tcod.CENTER)
1
>>> print(console)
<┌─┐╔═╗123/-\
 │ │║ ║456| |
 └─┘╚═╝789\-/
 ┌─ Title ──┐
 │          │
 └─┤Lower├──┘>
draw_rect(x: int, y: int, width: int, height: int, ch: int, fg: tuple[int, int, int] | None = None, bg: tuple[int, int, int] | None = None, bg_blend: int = 1) None[source]#

Draw characters and colors over a rectangular region.

x and y are the starting tile, with 0,0 as the upper-left corner of the console.

width and height determine the size of the rectangle.

ch is a Unicode integer. You can use 0 to leave the current characters unchanged.

fg and bg are the foreground text color and background tile color respectfully. This is a 3-item tuple with (r, g, b) color values from 0 to 255. These parameters can also be set to None to leave the colors unchanged.

bg_blend is the blend type used by libtcod.

New in version 8.5.

Changed in version 9.0: fg and bg now default to None instead of white-on-black.

Changed in version 13.0: x and y are now always used as an absolute position for negative values.

draw_semigraphics(pixels: ArrayLike | tcod.image.Image, x: int = 0, y: int = 0) None[source]#

Draw a block of 2x2 semi-graphics into this console.

pixels is an Image or an array-like object. It will be down-sampled into 2x2 blocks when drawn. Array-like objects must be in the shape of (height, width, RGB) and should have a dtype of numpy.uint8.

x and y is the upper-left tile position to start drawing.

New in version 11.4.

get_height_rect(x: int, y: int, width: int, height: int, string: str) int[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 (str) – A Unicode string.

Returns:

The number of lines of text once word-wrapped.

Return type:

int

hline(x: int, y: int, width: int, bg_blend: int = 13) None[source]#

Draw a horizontal line on the console.

This always uses ord(’─’), the horizontal line character.

Parameters:
  • x (int) – The x coordinate from the left.

  • y (int) – The y coordinate from the top.

  • width (int) – The horizontal length of this line.

  • bg_blend (int) – The background blending flag.

Deprecated since version 8.5: Console methods which depend on console defaults have been deprecated. Use Console.draw_rect instead, calling this function will print a warning detailing which default values need to be made explicit.

print(x: int, y: int, string: str, fg: tuple[int, int, int] | None = None, bg: tuple[int, int, int] | None = None, bg_blend: int = 1, alignment: int = 0) None[source]#

Print a string on a console with manual line breaks.

x and y are the starting tile, with 0,0 as the upper-left corner of the console.

string is a Unicode string which may include color control characters. Strings which are too long will be truncated until the next newline character "\n".

fg and bg are the foreground text color and background tile color respectfully. This is a 3-item tuple with (r, g, b) color values from 0 to 255. These parameters can also be set to None to leave the colors unchanged.

bg_blend is the blend type used by libtcod.

alignment can be tcod.LEFT, tcod.CENTER, or tcod.RIGHT.

New in version 8.5.

Changed in version 9.0: fg and bg now default to None instead of white-on-black.

Changed in version 13.0: x and y are now always used as an absolute position for negative values.

print_(x: int, y: int, string: str, bg_blend: int = 13, alignment: int | None = None) 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 (str) – A Unicode string optionally using color codes.

  • bg_blend (int) – Blending mode to use, defaults to BKGND_DEFAULT.

  • alignment (Optional[int]) – Text alignment.

Deprecated since version 8.5: Console methods which depend on console defaults have been deprecated. Use Console.print instead, calling this function will print a warning detailing which default values need to be made explicit.

print_box(x: int, y: int, width: int, height: int, string: str, fg: tuple[int, int, int] | None = None, bg: tuple[int, int, int] | None = None, bg_blend: int = 1, alignment: int = 0) int[source]#

Print a string constrained to a rectangle and return the height.

x and y are the starting tile, with 0,0 as the upper-left corner of the console.

width and height determine the bounds of the rectangle, the text will automatically be word-wrapped to fit within these bounds.

string is a Unicode string which may include color control characters.

fg and bg are the foreground text color and background tile color respectfully. This is a 3-item tuple with (r, g, b) color values from 0 to 255. These parameters can also be set to None to leave the colors unchanged.

bg_blend is the blend type used by libtcod.

alignment can be tcod.LEFT, tcod.CENTER, or tcod.RIGHT.

Returns the actual height of the printed area.

New in version 8.5.

Changed in version 9.0: fg and bg now default to None instead of white-on-black.

Changed in version 13.0: x and y are now always used as an absolute position for negative values.

print_frame(x: int, y: int, width: int, height: int, string: str = '', clear: bool = True, bg_blend: int = 13) None[source]#

Draw a framed rectangle with optional 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. If string is empty then no title will be drawn.

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 (str) – 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.

Changed in version 8.2: Now supports Unicode strings.

Deprecated since version 8.5: Console methods which depend on console defaults have been deprecated. Use Console.draw_frame instead, calling this function will print a warning detailing which default values need to be made explicit.

print_rect(x: int, y: int, width: int, height: int, string: str, bg_blend: int = 13, alignment: int | None = None) int[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 (str) – 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

Deprecated since version 8.5: Console methods which depend on console defaults have been deprecated. Use Console.print_box instead, calling this function will print a warning detailing which default values need to be made explicit.

put_char(x: int, y: int, ch: int, bg_blend: int = 13) None[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: int, y: int, width: int, height: int, clear: bool, bg_blend: int = 13) None[source]#

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

If clear 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.

Deprecated since version 8.5: Console methods which depend on console defaults have been deprecated. Use Console.draw_rect instead, calling this function will print a warning detailing which default values need to be made explicit.

set_key_color(color: tuple[int, int, int] | None) None[source]#

Set a consoles blit transparent color.

color is the (r, g, b) color, or None to disable key color.

Deprecated since version 8.5: Pass the key color to Console.blit instead of calling this function.

vline(x: int, y: int, height: int, bg_blend: int = 13) None[source]#

Draw a vertical line on the console.

This always uses ord(’│’), the vertical line character.

Parameters:
  • x (int) – The x coordinate from the left.

  • y (int) – The y coordinate from the top.

  • height (int) – The horizontal length of this line.

  • bg_blend (int) – The background blending flag.

Deprecated since version 8.5: Console methods which depend on console defaults have been deprecated. Use Console.draw_rect instead, calling this function will print a warning detailing which default values need to be made explicit.

property bg: NDArray[np.uint8]#

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[i, j, channel]  # order='C' or console.bg[x, y, channel]  # order='F'.

property buffer: NDArray[Any]#

An array of this consoles raw tile data.

New in version 11.4.

Deprecated since version 11.8: Use Console.rgba instead.

property ch: NDArray[np.intc]#

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[i, j]  # order='C' or console.ch[x, y]  # order='F'.

property default_alignment: int#

The default text alignment.

Type:

int

property default_bg: tuple[int, int, int]#

The default background color.

Type:

Tuple[int, int, int]

property default_bg_blend: int#

The default blending mode.

Type:

int

property default_fg: tuple[int, int, int]#

The default foreground color.

Type:

Tuple[int, int, int]

property fg: NDArray[np.uint8]#

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[i, j, channel]  # order='C' or console.fg[x, y, channel]  # order='F'.

property height: int#

The height of this Console.

property rgb: NDArray[Any]#

An array of this consoles data without the alpha channel.

The axes of this array is affected by the order parameter given to initialize the console.

The rgb_graphic dtype can be used to make arrays compatible with this attribute that are independent of a Console.

Example

>>> con = tcod.console.Console(10, 2)
>>> BLUE, YELLOW, BLACK = (0, 0, 255), (255, 255, 0), (0, 0, 0)
>>> con.rgb[0, 0] = ord("@"), YELLOW, BLACK
>>> con.rgb[0, 0]
(64, [255, 255,   0], [0, 0, 0])
>>> con.rgb["bg"] = BLUE
>>> con.rgb[0, 0]
(64, [255, 255,   0], [  0,   0, 255])

New in version 12.3.

property rgba: NDArray[Any]#

An array of this consoles raw tile data.

The axes of this array is affected by the order parameter given to initialize the console.

Example

>>> con = tcod.console.Console(10, 2)
>>> WHITE, BLACK = (255, 255, 255), (0, 0, 0)
>>> con.rgba[0, 0] = (
...     ord("X"),
...     (*WHITE, 255),
...     (*BLACK, 255),
... )
>>> con.rgba[0, 0]
(88, [255, 255, 255, 255], [  0,   0,   0, 255])

New in version 12.3.

property tiles: NDArray[Any]#

An array of this consoles raw tile data.

This acts as a combination of the ch, fg, and bg attributes. Colors include an alpha channel but how alpha works is currently undefined.

New in version 10.0.

Deprecated since version 12.3: Use Console.rgba instead.

property tiles2: NDArray[Any]#

This name is deprecated in favour of rgb.

New in version 11.3.

Deprecated since version 11.8: Use Console.rgb instead.

property tiles_rgb: NDArray[Any]#

An array of this consoles data without the alpha channel.

New in version 11.8.

Deprecated since version 12.3: Use Console.rgb instead.

property width: int#

The width of this Console.

tcod.console.get_height_rect(width: int, string: str) int[source]#

Return the number of lines which would be printed from these parameters.

width is the width of the print boundary.

string is a Unicode string which may include color control characters.

New in version 9.2.

tcod.console.load_xp(path: str | PathLike[str], order: Literal['C', 'F'] = 'C') tuple[Console, ...][source]#

Load a REXPaint file as a tuple of consoles.

path is the name of the REXPaint file to load. Usually ending with .xp.

order is the memory order of the Console’s array buffer, see tcod.console.Console.

New in version 12.4.

Example:

import numpy as np
import tcod.console
import tcod.tileset

path = "example.xp"  # REXPaint file with one layer.

# Load a REXPaint file with a single layer.
# The comma after console is used to unpack a single item tuple.
console, = tcod.console.load_xp(path, order="F")

# Convert tcod's Code Page 437 character mapping into a NumPy array.
CP437_TO_UNICODE = np.asarray(tcod.tileset.CHARMAP_CP437)

# Convert from REXPaint's CP437 encoding to Unicode in-place.
console.ch[:] = CP437_TO_UNICODE[console.ch]

# Apply REXPaint's alpha key color.
KEY_COLOR = (255, 0, 255)
is_transparent = (console.rgb["bg"] == KEY_COLOR).all(axis=-1)
console.rgba[is_transparent] = (ord(" "), (0,), (0,))
tcod.console.recommended_size() tuple[int, int][source]#

Return the recommended size of a console for the current active window.

The return is determined from the active tileset size and active window size. This result should be used create an Console instance.

This function will raise RuntimeError if libtcod has not been initialized.

New in version 11.8.

Deprecated since version 11.13: This function does not support contexts. Use Context.recommended_console_size instead.

tcod.console.save_xp(path: str | PathLike[str], consoles: Iterable[Console], compress_level: int = 9) None[source]#

Save tcod Consoles to a REXPaint file.

path is where to save the file.

consoles are the tcod.console.Console objects to be saved.

compress_level is the zlib compression level to be used.

Color alpha will be lost during saving.

Consoles will be saved as-is as much as possible. You may need to convert characters from Unicode to CP437 if you want to load the file in REXPaint.

New in version 12.4.

Example:

import numpy as np
import tcod.console
import tcod.tileset

console = tcod.console.Console(80, 24)  # Example console.

# Convert from Unicode to REXPaint's encoding.
# Required to load this console correctly in the REXPaint tool.

# Convert tcod's Code Page 437 character mapping into a NumPy array.
CP437_TO_UNICODE = np.asarray(tcod.tileset.CHARMAP_CP437)

# Initialize a Unicode-to-CP437 array.
# 0x20000 is the current full range of Unicode.
# fill_value=ord("?") means that "?" will be the result of any unknown codepoint.
UNICODE_TO_CP437 = np.full(0x20000, fill_value=ord("?"))
# Assign the CP437 mappings.
UNICODE_TO_CP437[CP437_TO_UNICODE] = np.arange(len(CP437_TO_UNICODE))

# Convert from Unicode to CP437 in-place.
console.ch[:] = UNICODE_TO_CP437[console.ch]

# Convert console alpha into REXPaint's alpha key color.
KEY_COLOR = (255, 0, 255)
is_transparent = console.rgba["bg"][:, :, 3] == 0
console.rgb["bg"][is_transparent] = KEY_COLOR

tcod.console.save_xp("example.xp", [console])
tcod.console.rgb_graphic = dtype([('ch', '<i4'), ('fg', 'u1', (3,)), ('bg', 'u1', (3,))])#

A NumPy dtype compatible with Console.rgb.

This dtype is: np.dtype([("ch", np.intc), ("fg", "3B"), ("bg", "3B")])

New in version 12.3.

tcod.console.rgba_graphic = dtype([('ch', '<i4'), ('fg', 'u1', (4,)), ('bg', 'u1', (4,))])#

A NumPy dtype compatible with Console.rgba.

This dtype is: np.dtype([("ch", np.intc), ("fg", "4B"), ("bg", "4B")])

New in version 12.3.