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 ____________________>
Added in version 8.5.
Changed in version 10.0: Added an alpha channel to the color types.
- __enter__() Self [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.
See also
- __exit__(*_: object) None [source]¶
Close the graphical window on exit.
Some tcod functions may have undefined behavior after this point.
- 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
.Added in version 11.11.
- draw_frame(x: int, y: int, width: int, height: int, *, clear: bool = True, fg: tuple[int, int, int] | None = None, bg: tuple[int, int, int] | None = None, bg_blend: int = tcod.constants.BKGND_SET, decoration: str | tuple[int, int, int, int, int, int, int, int, int] = '┌─┐│ │└─┘') None [source]¶
- 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 = tcod.constants.BKGND_SET, *, decoration: str | tuple[int, int, int, int, int, int, int, int, int] = '┌─┐│ │└─┘') None
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. Must be given as a keyword argument.
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. Must be given as a keyword argument.
bg_blend is the blend type used by libtcod. Must be given as a keyword argument.
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.
Added 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.
Changed in version 18.0: Deprecated clear, fg, bg, and bg_blend being given as positional arguments. These should be keyword arguments only.
Example:
>>> from tcod import libtcodpy >>> 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(x=0, y=3, width=12, height=1, string=" Title ", alignment=libtcodpy.CENTER) 1 >>> console.print(x=0, y=5, width=12, height=1, string="┤Lower├", alignment=libtcodpy.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 = tcod.constants.BKGND_SET) None [source]¶
- 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 = tcod.constants.BKGND_SET) None
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. Must be given as a keyword argument.
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. Must be given as a keyword argument.
bg_blend is the blend type used by libtcod. Must be given as a keyword argument.
Added 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.
Changed in version 18.0: Deprecated ch, fg, bg, and bg_blend being given as positional arguments. These should be keyword arguments only.
- 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.
Added 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.
- 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:
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, text: str, *, width: int | None = None, height: int | None = None, fg: tuple[int, int, int] | None = None, bg: tuple[int, int, int] | None = None, bg_blend: int = tcod.constants.BKGND_SET, alignment: int = tcod.constants.LEFT) int [source]¶
- print(x: int, y: int, text: str, fg: tuple[int, int, int] | None = None, bg: tuple[int, int, int] | None = None, bg_blend: int = tcod.constants.BKGND_SET, alignment: int = tcod.constants.LEFT, *, string: str = '') int
Print a string of Unicode text on this console.
Prefer using keywords for this method call to avoid ambiguous parameters.
- Parameters:
x – Starting X coordinate, with the left-most tile as zero.
y – Starting Y coordinate, with the top-most tile as zero.
text – A Unicode string which may include color control characters.
width – Width in tiles to constrain the printing region. If a width is given then text will have automatic word wrapping applied to it. A width of None means text will only have manual line breaks.
height – Height in tiles to constrain the printing region.
fg – RGB tuple to use as the foreground color, or None to leave the foreground unchanged. Tuple values should be 0-255. Must be given as a keyword argument.
bg – RGB tuple to use as the background color, or None to leave the foreground unchanged. Tuple values should be 0-255. Must be given as a keyword argument.
bg_blend – Background blend type used by libtcod. Typically starts with libtcodpy.BKGND_*. Must be given as a keyword argument.
alignment – One of libtcodpy.LEFT, libtcodpy.CENTER, or libtcodpy.RIGHT Must be given as a keyword argument.
string – Older deprecated name of the text parameter.
- Returns:
The height of text in lines via word wrapping and line breaks.
Example:
>>> from tcod import libtcodpy >>> console = tcod.console.Console(20, 1) >>> console.clear(ch=ord('·')) >>> console.print(x=0, y=0, text="left") 1 >>> console.print(x=console.width, y=0, text="right", alignment=libtcodpy.RIGHT) 1 >>> console.print(x=10, y=0, text="center", alignment=libtcodpy.CENTER) 1 >>> print(console) <left···center··right> >>> console = tcod.console.Console(20, 4) >>> console.clear(ch=ord('·')) >>> console.print(x=1, y=1, text="words within bounds", width=8) 3 >>> print(console) <···················· ·words·············· ·within············· ·bounds·············> >>> WHITE = (255, 255, 255) >>> BLACK = (0, 0, 0) >>> console.print(x=0, y=0, text="Black text on white background", fg=BLACK, bg=WHITE) 1
Added 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.
Changed in version 18.0: Deprecated giving string, fg, bg, and bg_blend as positional arguments.
Added text parameter to replace string.
Added width and height keyword parameters to bind text to a rectangle and replace other print functions. Right-aligned text with width=None now treats the x coordinate as a past-the-end index, this will shift the text of older calls to the left by 1 tile.
Now returns the number of lines printed via word wrapping, same as previous print functions bound to rectangles.
- 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:
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.
Added 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:
- Returns:
The number of lines of text once word-wrapped.
- Return type:
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.
- 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:
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:
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'
orconsole.bg[x, y, channel] # order='F'
.
- property buffer: NDArray[Any]¶
An array of this consoles raw tile data.
Added 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'
orconsole.ch[x, y] # order='F'
.
- property default_alignment: int¶
The default text alignment.
Deprecated since version 8.5: These should not be used. Prefer passing defaults as kwargs.
- Type:
- property default_bg: tuple[int, int, int]¶
The default background color.
Deprecated since version 8.5: These should not be used. Prefer passing defaults as kwargs.
DEFAULT_COLOR = {"bg": (0, 0, 127), "fg": (127, 127, 255)} console.print(x, y, string, **DEFAULT_COLOR)
- property default_bg_blend: int¶
The default blending mode.
Deprecated since version 8.5: These should not be used. Prefer passing defaults as kwargs.
- Type:
- property default_fg: tuple[int, int, int]¶
The default foreground color.
Deprecated since version 8.5: These should not be used. Prefer passing defaults as kwargs.
- 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'
orconsole.fg[x, y, channel] # order='F'
.
- 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 aConsole
.Example
>>> tile_graphics = np.array( # Tile graphics lookup table ... [ # (Unicode, foreground, background) ... (ord("."), (255, 255, 255), (0, 0, 0)), # Tile 0 ... (ord("#"), (255, 255, 255), (0, 0, 0)), # Tile 1 ... (ord("^"), (255, 255, 255), (0, 0, 0)), # Tile 2 ... (ord("~"), (255, 255, 255), (0, 0, 0)), # Tile 3 ... ], ... dtype=tcod.console.rgb_graphic, ... ) >>> console = tcod.console.Console(6, 5) >>> console.rgb[:] = tile_graphics[ # Convert 2D array of indexes to tile graphics ... [ ... [1, 1, 1, 1, 1, 1], ... [1, 0, 2, 0, 0, 1], ... [1, 0, 0, 3, 3, 1], ... [1, 0, 0, 3, 3, 1], ... [1, 1, 1, 1, 1, 1], ... ], ... ] >>> print(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 >>> print(f"{con.rgb[0, 0]=}") con.rgb[0, 0]=...(64, [255, 255, 0], [0, 0, 0])... >>> con.rgb["bg"] = BLUE >>> print(f"{con.rgb[0, 0]=}") con.rgb[0, 0]=...(64, [255, 255, 0], [ 0, 0, 255])...
Added 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), ... ) >>> print(f"{con.rgba[0, 0]=}") con.rgba[0, 0]=...(88, [255, 255, 255, 255], [ 0, 0, 0, 255])...
Added 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.
Added 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
.Added 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.
Added in version 11.8.
Deprecated since version 12.3: Use
Console.rgb
instead.
- 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.
Added 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
.Added 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.
Added 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.
Added 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[Any] = dtype([('ch', '<i4'), ('fg', 'u1', (3,)), ('bg', 'u1', (3,))])¶
A NumPy
dtype
compatible withConsole.rgb
.This dtype is:
np.dtype([("ch", np.intc), ("fg", "3B"), ("bg", "3B")])
Added in version 12.3.
- tcod.console.rgba_graphic: dtype[Any] = dtype([('ch', '<i4'), ('fg', 'u1', (4,)), ('bg', 'u1', (4,))])¶
A NumPy
dtype
compatible withConsole.rgba
.This dtype is:
np.dtype([("ch", np.intc), ("fg", "4B"), ("bg", "4B")])
Added in version 12.3.