tdl

Getting Started

Once the library is imported you can load the font you want to use with tdl.set_font. This is optional and when skipped will use a decent default font.

After that you call tdl.init to set the size of the window and get the root console in return. This console is the canvas to what will appear on the screen.

Indexing Consoles

For most methods taking a position you can use Python-style negative indexes to refer to the opposite side of a console with (-1, -1) starting at the bottom right. You can also check if a point is part of a console using containment logic i.e. ((x, y) in console).

You may also iterate over a console using a for statement. This returns every x,y coordinate available to draw on but it will be extremely slow to actually operate on every coordinate individualy. Try to minimize draws by using an offscreen Console, only drawing what needs to be updated, and using Console.blit.

Drawing and Colors

Once you have the root console from tdl.init you can start drawing on it using a method such as Console.draw_char. When using this method you can have the char parameter be an integer or a single character string.

The fg and bg parameters expect a variety of types. The parameters default to Ellipsis which will tell the function to use the colors previously set by the Console.set_colors method. The colors set by :any`Console.set_colors` are per each Console/Window and default to white on black. You can use a 3-item list/tuple of [red, green, blue] with integers in the 0-255 range with [0, 0, 0] being black and [255, 255, 255] being white. You can even use a single integer of 0xRRGGBB if you like.

Using None in the place of any of the three parameters (char, fg, bg) will tell the function to not overwrite that color or character.

After the drawing functions are called a call to tdl.flush will update the screen.

tdl API

tdl.set_font(path, columns=None, rows=None, columnFirst=False, greyscale=False, altLayout=False)[source]

Changes the font to be used for this session. This should be called before tdl.init

If the font specifies its size in its filename (i.e. font_NxN.png) then this function can auto-detect the tileset formatting and the parameters columns and rows can be left None.

While it’s possible you can change the font mid program it can sometimes break in rare circumstances. So use caution when doing this.

Parameters:
  • path (Text) – A file path to a .bmp or .png file.
  • columns (int) –

    Number of columns in the tileset.

    Can be left None for auto-detection.

  • rows (int) –

    Number of rows in the tileset.

    Can be left None for auto-detection.

  • columnFirst (bool) –

    Defines if the characer order goes along the rows or colomns.

    It should be True if the charater codes 0-15 are in the first column, and should be False if the characters 0-15 are in the first row.

  • greyscale (bool) –

    Creates an anti-aliased font from a greyscale bitmap. Otherwise it uses the alpha channel for anti-aliasing.

    Unless you actually need anti-aliasing from a font you know uses a smooth greyscale channel you should leave this on False.

  • altLayout (bool) – An alternative layout with space in the upper left corner. The colomn parameter is ignored if this is True, find examples of this layout in the font/libtcod/ directory included with the python-tdl source.
Raises:

TDLError – Will be raised if no file is found at path or if auto- detection fails.

tdl.init(width, height, title=None, fullscreen=False, renderer=u'SDL')[source]

Start the main console with the given width and height and return the root console.

Call the consoles drawing functions. Then remember to use L{tdl.flush} to make what’s drawn visible on the console.

Parameters:
  • width (int) – width of the root console (in tiles)
  • height (int) – height of the root console (in tiles)
  • title (Optiona[Text]) –

    Text to display as the window title.

    If left None it defaults to the running scripts filename.

  • fullscreen (bool) – Can be set to True to start in fullscreen mode.
  • renderer (Text) – Can be one of ‘GLSL’, ‘OPENGL’, or ‘SDL’.
  • to way Python works you're unlikely to see much of an (Due) –
  • by using 'GLSL' over 'OPENGL' as most of the (improvement) –
  • Python is slow interacting with the console and the (time) –
  • itself is pretty fast even on 'SDL'. (rendering) –
Returns:

The root console.

Only what is drawn on the root console is what’s visible after a call to tdl.flush. After the root console is garbage collected, the window made by this function will close.

Return type:

tdl.Console

See also

Console set_font

tdl.flush()[source]

Make all changes visible and update the screen.

Remember to call this function after drawing operations. Calls to flush will enfore the frame rate limit set by tdl.set_fps.

This function can only be called after tdl.init

tdl.screenshot(path=None)[source]

Capture the screen and save it as a png file.

If path is None then the image will be placed in the current folder with the names: screenshot001.png, screenshot002.png, ...

Parameters:path (Optional[Text]) – The file path to save the screenshot.
tdl.get_fullscreen()[source]

Returns True if program is fullscreen.

Returns:
Returns True if the application is in full-screen mode.
Otherwise returns False.
Return type:bool
tdl.set_fullscreen(fullscreen)[source]

Changes the fullscreen state.

Parameters:fullscreen (bool) – True for full-screen, False for windowed mode.
tdl.set_title(title)[source]

Change the window title.

Parameters:title (Text) – The new title text.
tdl.get_fps()[source]

Return the current frames per second of the running program set by set_fps

Returns:
The frame rate set by set_fps.
If there is no current limit, this will return 0.
Return type:int
tdl.set_fps(fps)[source]

Set the maximum frame rate.

Further calls to tdl.flush will limit the speed of the program to run at fps frames per second. This can also be set to None to remove the frame rate limit.

Parameters:fps (optional[int]) – The frames per second limit, or None.
tdl.force_resolution(width, height)[source]

Change the fullscreen resoulution.

Parameters:
  • width (int) – Width in pixels.
  • height (int) – Height in pixels.
exception tdl.TDLError[source]

The catch all for most TDL specific errors.

tdl.Console

class tdl.Console(width, height)[source]

Contains character and color data and can be drawn to.

The console created by the tdl.init function is the root console and is the console that is rendered to the screen with flush.

Any console created from the Console class is an off-screen console that can be drawn on before being blit to the root console.

Parameters:
  • width (int) – Width of the new console in tiles
  • height (int) – Height of the new console in tiles
__del__()[source]

If the main console is garbage collected then the window will be closed as well

__format__()

default object formatter

__reduce__()

helper for pickle

__reduce_ex__()

helper for pickle

__sizeof__() → int

size of object in memory, in bytes

blit(source, x=0, y=0, width=None, height=None, srcX=0, srcY=0, fg_alpha=1.0, bg_alpha=1.0)

Blit another console or Window onto the current console.

By default it blits the entire source to the topleft corner.

Parameters:
  • source (Union[tdl.Console, tdl.Window]) – The blitting source. A console can blit to itself without any problems.
  • x (int) – x-coordinate of this console to blit on.
  • y (int) – y-coordinate of this console to blit on.
  • width (Optional[int]) –

    Width of the rectangle.

    Can be None to extend as far as possible to the bottom right corner of the blit area or can be a negative number to be sized reltive to the total size of the B{destination} console.

  • height (Optional[int]) – Height of the rectangle.
  • srcX (int) – x-coordinate of the source region to blit.
  • srcY (int) – y-coordinate of the source region to blit.
  • fg_alpha (float) – The foreground alpha.
clear(fg=Ellipsis, bg=Ellipsis)[source]

Clears the entire L{Console}/L{Window}.

Unlike other drawing functions, fg and bg can not be None.

Parameters:

See also

draw_rect

draw_char(x, y, char, fg=Ellipsis, bg=Ellipsis)

Draws a single character.

Parameters:
  • x (int) – x-coordinate to draw on.
  • y (int) – y-coordinate to draw on.
  • char (Optional[Union[int, Text]]) –

    An integer, single character string, or None.

    You can set the char parameter as None if you only want to change the colors of the tile.

  • fg (Optional[Union[Tuple[int, int, int], int, Ellipsis]]) –
  • bg (Optional[Union[Tuple[int, int, int], int, Ellipsis]]) –
Raises: AssertionError: Having x or y values that can’t be placed
inside of the console will raise an AssertionError. You can use always use ((x, y) in console) to check if a tile is drawable.

See also

get_char

draw_frame(x, y, width, height, string, fg=Ellipsis, bg=Ellipsis)

Similar to L{draw_rect} but only draws the outline of the rectangle.

width or `height can be None to extend to the bottom right of the console or can be a negative number to be sized reltive to the total size of the console.

Parameters:
  • x (int) – The x-coordinate to start on.
  • y (int) – The y-coordinate to start on.
  • width (Optional[int]) – Width of the rectangle.
  • height (Optional[int]) – Height of the rectangle.
  • string (Optional[Union[Text, int]]) –

    An integer, single character string, or None.

    You can set this parameter as None if you only want to change the colors of an area.

  • fg (Optional[Union[Tuple[int, int, int], int, Ellipsis]]) –
  • bg (Optional[Union[Tuple[int, int, int], int, Ellipsis]]) –
Raises:
AssertionError – Having x or y values that can’t be placed inside

of the console will raise an AssertionError.

You can use always use ((x, y) in console) to check if a tile is drawable.

See also

draw_rect, Window

draw_rect(x, y, width, height, string, fg=Ellipsis, bg=Ellipsis)

Draws a rectangle starting from x and y and extending to width and height.

If width or height are None then it will extend to the edge of the console.

Parameters:
  • x (int) – x-coordinate for the top side of the rect.
  • y (int) – y-coordinate for the left side of the rect.
  • width (Optional[int]) –

    The width of the rectangle.

    Can be None to extend to the bottom right of the console or can be a negative number to be sized reltive to the total size of the console.

  • height (Optional[int]) – The height of the rectangle.
  • string (Optional[Union[Text, int]]) –

    An integer, single character string, or None.

    You can set the string parameter as None if you only want to change the colors of an area.

  • fg (Optional[Union[Tuple[int, int, int], int, Ellipsis]]) –
  • bg (Optional[Union[Tuple[int, int, int], int, Ellipsis]]) –
Raises:
  • AssertionError – Having x or y values that can’t be placed inside of the console will raise an AssertionError.
  • You can use always use ((x, y) in console) to check if a tile
  • is drawable.

See also

clear, draw_frame

draw_str(x, y, string, fg=Ellipsis, bg=Ellipsis)

Draws a string starting at x and y.

A string that goes past the right side will wrap around. A string wrapping to below the console will raise tdl.TDLError but will still be written out. This means you can safely ignore the errors with a try..except block if you’re fine with partially written strings.

r and n are drawn on the console as normal character tiles. No special encoding is done and any string will translate to the character table as is.

For a string drawing operation that respects special characters see print_str.

Parameters:
  • x (int) – x-coordinate to start at.
  • y (int) – y-coordinate to start at.
  • string (Union[Text, Iterable[int]]) –

    A string or an iterable of numbers.

    Special characters are ignored and rendered as any other character.

  • fg (Optional[Union[Tuple[int, int, int], int, Ellipsis]]) –
  • bg (Optional[Union[Tuple[int, int, int], int, Ellipsis]]) –
Raises:
AssertionError – Having x or y values that can’t be placed inside

of the console will raise an AssertionError.

You can use always use ((x, y) in console) to check if a tile is drawable.

See also

print_str

get_char(x, y)[source]

Return the character and colors of a tile as (ch, fg, bg)

This method runs very slowly as is not recommended to be called frequently.

Parameters:
  • x (int) – The x-coordinate to pick.
  • y (int) – The y-coordinate to pick.
Returns:

A 3-item

tuple: (int, fg, bg)

The first item is an integer of the character at the position (x, y) the second and third are the foreground and background colors respectfully.

Return type:

Tuple[int, Tuple[int, int, int], Tuple[int, int, int]]

See also

draw_char

get_cursor()

Return the virtual cursor position.

The cursor can be moved with the move method.

Returns:
The (x, y) coordinate of where print_str
will continue from.
Return type:Tuple[int, int]

See also

:any:move`

get_size()

Return the size of the console as (width, height)

Returns:A (width, height) tuple.
Return type:Tuple[int, int]
move(x, y)

Move the virtual cursor.

Parameters:
  • x (int) – x-coordinate to place the cursor.
  • y (int) – y-coordinate to place the cursor.
print_str(string)

Print a string at the virtual cursor.

Handles special characters such as ‘n’ and ‘r’. Printing past the bottom of the console will scroll everything upwards if set_mode is set to ‘scroll’.

Colors can be set with set_colors and the virtual cursor can be moved with move.

Parameters:string (Text) – The text to print.
scroll(x, y)

Scroll the contents of the console in the direction of x,y.

Uncovered areas will be cleared to the default background color. Does not move the virutal cursor.

Parameters:
  • x (int) – Distance to scroll along the x-axis.
  • y (int) – Distance to scroll along the y-axis.
Returns:

An iterator over the (x, y) coordinates of any tile uncovered after scrolling.

Return type:

Iterator[Tuple[int, int]]

See also

set_colors

set_colors(fg=None, bg=None)

Sets the colors to be used with the L{print_str} and draw_* methods.

Values of None will only leave the current values unchanged.

Parameters:

See also

move, print_str

set_mode(mode)

Configure how this console will react to the cursor writing past the end if the console.

This is for methods that use the virtual cursor, such as print_str.

Parameters:
  • mode (Text) – The mode to set.
  • settings are (Possible) –
    • ‘error’ - A TDLError will be raised once the cursor reaches the end of the console. Everything up until the error will still be drawn. This is the default setting.
    • ‘scroll’ - The console will scroll up as stuff is written to the end. You can restrict the region with tdl.Window when doing this.

..seealso:: write, print_str

write(string)

This method mimics basic file-like behaviour.

Because of this method you can replace sys.stdout or sys.stderr with a Console or Window instance.

This is a convoluted process and behaviour seen now can be excepted to change on later versions.

Parameters:string (Text) – The text to write out.
__delattr__

x.__delattr__(‘name’) <==> del x.name

__getattribute__

x.__getattribute__(‘name’) <==> x.name

__hash__
__setattr__

x.__setattr__(‘name’, value) <==> x.name = value

__str__

tdl.Window

class tdl.Window(console, x, y, width, height)[source]

Isolate part of a Console or Window instance.

This classes methods are the same as tdl.Console

Making a Window and setting its width or height to None will extend it to the edge of the console.

This follows the normal rules for indexing so you can use a negative integer to place the Window relative to the bottom right of the parent Console instance.

width or height can be set to None to extend as far as possible to the bottom right corner of the parent Console or can be a negative number to be sized reltive to the Consoles total size.

Parameters:
  • console (Union(tdl.Console, tdl.Window)) – The parent object.
  • x (int) – x-coordinate to place the Window.
  • y (int) – y-coordinate to place the Window.
  • width (Optional[int]) – Width of the Window.
  • height (Optional[int]) – Height of the Window.

tdl.event

This module handles user input.

To handle user input you will likely want to use the event.get function or create a subclass of event.App.

But there are other options such as event.key_wait and event.is_window_closed.

A few event attributes are actually string constants. Here’s a reference for those:

  • Event.type: ‘QUIT’, ‘KEYDOWN’, ‘KEYUP’, ‘MOUSEDOWN’, ‘MOUSEUP’, or ‘MOUSEMOTION.’
  • MouseButtonEvent.button (found in MouseDown and MouseUp events): ‘LEFT’, ‘MIDDLE’, ‘RIGHT’, ‘SCROLLUP’, ‘SCROLLDOWN’
  • KeyEvent.key (found in KeyDown and KeyUp events): ‘NONE’, ‘ESCAPE’, ‘BACKSPACE’, ‘TAB’, ‘ENTER’, ‘SHIFT’, ‘CONTROL’, ‘ALT’, ‘PAUSE’, ‘CAPSLOCK’, ‘PAGEUP’, ‘PAGEDOWN’, ‘END’, ‘HOME’, ‘UP’, ‘LEFT’, ‘RIGHT’, ‘DOWN’, ‘PRINTSCREEN’, ‘INSERT’, ‘DELETE’, ‘LWIN’, ‘RWIN’, ‘APPS’, ‘0’, ‘1’, ‘2’, ‘3’, ‘4’, ‘5’, ‘6’, ‘7’, ‘8’, ‘9’, ‘KP0’, ‘KP1’, ‘KP2’, ‘KP3’, ‘KP4’, ‘KP5’, ‘KP6’, ‘KP7’, ‘KP8’, ‘KP9’, ‘KPADD’, ‘KPSUB’, ‘KPDIV’, ‘KPMUL’, ‘KPDEC’, ‘KPENTER’, ‘F1’, ‘F2’, ‘F3’, ‘F4’, ‘F5’, ‘F6’, ‘F7’, ‘F8’, ‘F9’, ‘F10’, ‘F11’, ‘F12’, ‘NUMLOCK’, ‘SCROLLLOCK’, ‘SPACE’, ‘CHAR’
class tdl.event.Quit[source]

Fired when the window is closed by the user.

class tdl.event.MouseUp(button, pos, cell)[source]

Fired when a mouse button is released.

class tdl.event.KeyDown(key='', char='', text='', shift=False, left_alt=False, right_alt=False, left_control=False, right_control=False, left_meta=False, right_meta=False)[source]

Fired when the user presses a key on the keyboard or a key repeats.

class tdl.event.MouseMotion(pos, cell, motion, cellmotion)[source]

Fired when the mouse is moved.

cell = None

(x, y) position of the mouse snapped to a cell on the root console. type: (int, int)

cellmotion = None

(x, y) mostion of the mouse moving over cells on the root console. type: (int, int)

motion = None

(x, y) motion of the mouse on the screen. type: (int, int)

pos = None

(x, y) position of the mouse on the screen. type: (int, int)

class tdl.event.MouseButtonEvent(button, pos, cell)[source]

Base class for mouse button events.

button = None

Text – Can be one of ‘LEFT’, ‘MIDDLE’, ‘RIGHT’, ‘SCROLLUP’, ‘SCROLLDOWN’

cell = None

Tuple[int, int] – (x, y) position of the mouse snapped to a cell on the root console

pos = None

Tuple[int, int] – (x, y) position of the mouse on the screen.

class tdl.event.MouseDown(button, pos, cell)[source]

Fired when a mouse button is pressed.

class tdl.event.KeyEvent(key='', char='', text='', shift=False, left_alt=False, right_alt=False, left_control=False, right_control=False, left_meta=False, right_meta=False)[source]

Base class for key events.

alt = None

bool – True if alt was held down during this event.

char = None

Text – A single character string of the letter or symbol pressed.

Special characters like delete and return are not cross-platform. L{key} or L{keychar} should be used instead for special keys. Characters are also case sensitive.

control = None

bool – True if control was held down during this event.

key = None

Text – Human readable names of the key pressed. Non special characters will show up as ‘CHAR’.

Can be one of ‘NONE’, ‘ESCAPE’, ‘BACKSPACE’, ‘TAB’, ‘ENTER’, ‘SHIFT’, ‘CONTROL’, ‘ALT’, ‘PAUSE’, ‘CAPSLOCK’, ‘PAGEUP’, ‘PAGEDOWN’, ‘END’, ‘HOME’, ‘UP’, ‘LEFT’, ‘RIGHT’, ‘DOWN’, ‘PRINTSCREEN’, ‘INSERT’, ‘DELETE’, ‘LWIN’, ‘RWIN’, ‘APPS’, ‘0’, ‘1’, ‘2’, ‘3’, ‘4’, ‘5’, ‘6’, ‘7’, ‘8’, ‘9’, ‘KP0’, ‘KP1’, ‘KP2’, ‘KP3’, ‘KP4’, ‘KP5’, ‘KP6’, ‘KP7’, ‘KP8’, ‘KP9’, ‘KPADD’, ‘KPSUB’, ‘KPDIV’, ‘KPMUL’, ‘KPDEC’, ‘KPENTER’, ‘F1’, ‘F2’, ‘F3’, ‘F4’, ‘F5’, ‘F6’, ‘F7’, ‘F8’, ‘F9’, ‘F10’, ‘F11’, ‘F12’, ‘NUMLOCK’, ‘SCROLLLOCK’, ‘SPACE’, ‘CHAR’

For the actual character instead of ‘CHAR’ use keychar.

keychar = None

Similar to L{key} but returns a case sensitive letter or symbol instead of ‘CHAR’.

This variable makes available the widest variety of symbols and should be used for key-mappings or anywhere where a narrower sample of keys isn’t needed.

leftAlt = None

bool

leftCtrl = None

bool

left_alt = None

bool

left_control = None

bool

rightAlt = None

bool

rightCtrl = None

bool

right_alt = None

bool

right_control = None

bool

shift = None

bool – True if shift was held down during this event.

class tdl.event.App[source]

Application framework.

  • ev_*: Events are passed to methods based on their Event.type attribute. If an event type is ‘KEYDOWN’ the ev_KEYDOWN method will be called with the event instance as a parameter.

  • key_*: When a key is pressed another method will be called based on the KeyEvent.key attribute. For example the ‘ENTER’ key will call key_ENTER with the associated KeyDown event as its parameter.

  • update: This method is called every loop. It is passed a single parameter detailing the time in seconds since the last update (often known as deltaTime.)

    You may want to call drawing routines in this method followed by tdl.flush.

ev_KEYDOWN(event)[source]

Override this method to handle a KeyDown event.

ev_KEYUP(event)[source]

Override this method to handle a KeyUp event.

ev_MOUSEDOWN(event)[source]

Override this method to handle a MouseDown event.

ev_MOUSEMOTION(event)[source]

Override this method to handle a MouseMotion event.

ev_MOUSEUP(event)[source]

Override this method to handle a MouseUp event.

ev_QUIT(event)[source]

Unless overridden this method raises a SystemExit exception closing the program.

run()[source]

Delegate control over to this App instance. This function will process all events and send them to the special methods ev_* and key_*.

A call to App.suspend will return the control flow back to where this function is called. And then the App can be run again. But a single App instance can not be run multiple times simultaneously.

run_once()[source]

Pump events to this App instance and then return.

This works in the way described in App.run except it immediately returns after the first update call.

Having multiple App instances and selectively calling runOnce on them is a decent way to create a state machine.

suspend()[source]

When called the App will begin to return control to where App.run was called.

Some further events are processed and the App.update method will be called one last time before exiting (unless suspended during a call to App.update.)

update(deltaTime)[source]

Override this method to handle per frame logic and drawing.

Parameters:deltaTime (float) –

This parameter tells the amount of time passed since the last call measured in seconds as a floating point number.

You can use this variable to make your program frame rate independent. Use this parameter to adjust the speed of motion, timers, and other game logic.

class tdl.event.KeyUp(key='', char='', text='', shift=False, left_alt=False, right_alt=False, left_control=False, right_control=False, left_meta=False, right_meta=False)[source]

Fired when the user releases a key on the keyboard.

class tdl.event.Event[source]

Base Event class.

You can easily subclass this to make your own events. Be sure to set the class attribute L{Event.type} for it to be passed to a custom App ev_* method.

__repr__()[source]

List an events public attributes when printed.

type = None

String constant representing the type of event.

The App ev_* methods depend on this attribute.

Can be: ‘QUIT’, ‘KEYDOWN’, ‘KEYUP’, ‘MOUSEDOWN’, ‘MOUSEUP’, or ‘MOUSEMOTION.’

tdl.event.key_wait()[source]

Waits until the user presses a key. Then returns a KeyDown event.

Key events will repeat if held down.

A click to close the window will be converted into an Alt+F4 KeyDown event.

Returns:The pressed key.
Return type:tdl.event.KeyDown
tdl.event.set_key_repeat(delay=500, interval=0)[source]

Does nothing.

tdl.event.get()[source]

Flushes the event queue and returns the list of events.

This function returns Event objects that can be identified by their type attribute or their class.

Returns: Iterator[Type[Event]]: An iterable of Events or anything

put in a push call.

If the iterator is deleted or otherwise interrupted before finishing the excess items are preserved for the next call.

tdl.event.wait(timeout=None, flush=True)[source]

Wait for an event.

Parameters:
  • timeout (Optional[int]) –

    The time in seconds that this function will wait before giving up and returning None.

    With the default value of None, this will block forever.

  • flush (bool) – If True a call to tdl.flush will be made before listening for events.
Returns: Type[Event]: An event, or None if the function
has timed out. Anything added via push will also be returned.
tdl.event.is_window_closed()[source]

Returns True if the exit button on the window has been clicked and stays True afterwards.

Returns: bool:

tdl.event.push(event)[source]

Push an event into the event buffer.

Parameters:event (Any) –

This event will be available on the next call to event.get.

An event pushed in the middle of a get will not show until the next time get called preventing push related infinite loops.

This object should at least have a ‘type’ attribute.

tdl.map

Rogue-like map utilitys such as line-of-sight, field-of-view, and path-finding.

Deprecated since version 3.2: The features provided here are better realized in the tcod.map and tcod.path modules.

class tdl.map.AStar(width, height, callback, diagnalCost=1.4142135623730951, advanced=False)[source]

An A* pathfinder using a callback.

Deprecated since version 3.2: See tcod.path.

Before crating this instance you should make one of two types of callbacks:

  • A function that returns the cost to move to (x, y)
  • A function that returns the cost to move between (destX, destY, sourceX, sourceY)

If path is blocked the function should return zero or None. When using the second type of callback be sure to set advanced=True

Parameters:
  • width (int) – Width of the pathfinding area (in tiles.)
  • height (int) – Height of the pathfinding area (in tiles.)
  • (Union[Callable[[int, int], float], (callback) –

    Callable[[int, int, int, int], float]]): A callback returning the cost of a tile or edge.

    A callback taking parameters depending on the setting of ‘advanced’ and returning the cost of movement for an open tile or zero for a blocked tile.

  • diagnalCost (float) –

    Multiplier for diagonal movement.

    Can be set to zero to disable diagonal movement entirely.

  • advanced (bool) –

    Give 2 additional parameters to the callback.

    A simple callback with 2 positional parameters may not provide enough information. Setting this to True will call the callback with 2 additional parameters giving you both the destination and the source of movement.

    When True the callback will need to accept (destX, destY, sourceX, sourceY) as parameters. Instead of just (destX, destY).

get_path(origX, origY, destX, destY)[source]

Get the shortest path from origXY to destXY.

Returns:
Returns a list walking the path from orig
to dest.

This excludes the starting point and includes the destination.

If no path is found then an empty list is returned.

Return type:List[Tuple[int, int]]
class tdl.map.Map(width, height)[source]

Field-of-view and path-finding on stored data.

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

Deprecated since version 3.2: tcod.map.Map should be used instead.

Set map conditions with the walkable and transparency attributes, this object can be iterated and checked for containment similar to consoles.

For example, you can set all tiles and transparent and walkable with the following code:

Example

>>> import tdl.map
>>> map_ = tdl.map.Map(80, 60)
>>> map_.transparent[:] = True
>>> map_.walkable[:] = True
transparent

Map transparency

Access this attribute with map.transparent[x,y]

Set to True to allow field-of-view rays, False will block field-of-view.

Transparent tiles only affect field-of-view.

walkable

Map accessibility

Access this attribute with map.walkable[x,y]

Set to True to allow path-finding through that tile, False will block passage to that tile.

Walkable tiles only affect path-finding.

fov

Map tiles touched by a field-of-view computation.

Access this attribute with map.fov[x,y]

Is True if a the tile is if view, otherwise False.

You can set to this attribute if you want, but you’ll typically be using it to read the field-of-view of a compute_fov call.

compute_fov(x, y, fov='PERMISSIVE', radius=None, light_walls=True, sphere=True, cumulative=False)[source]

Compute the field-of-view of this Map and return an iterator of the points touched.

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

    The type of field-of-view to be used.

    Available types are: ‘BASIC’, ‘DIAMOND’, ‘SHADOW’, ‘RESTRICTIVE’, ‘PERMISSIVE’, ‘PERMISSIVE0’, ‘PERMISSIVE1’, ..., ‘PERMISSIVE8’

  • radius (Optional[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.
  • sphere (bool) – If True the lit area will be round instead of square.
  • cumulative (bool) – If True the lit cells will accumulate instead of being cleared before the computation.
Returns:

An iterator of (x, y) points of tiles

touched by the field-of-view.

Return type:

Iterator[Tuple[int, int]]

compute_path(start_x, start_y, dest_x, dest_y, diagonal_cost=1.4142135623730951)[source]

Get the shortest path between two points.

Parameters:
  • start_x (int) – Starting x-position.
  • start_y (int) – Starting y-position.
  • dest_x (int) – Destination x-position.
  • dest_y (int) – Destination y-position.
  • diagonal_cost (float) –

    Multiplier for diagonal movement.

    Can be set to zero to disable diagonal movement entirely.

Returns:

The shortest list of points to the

destination position from the starting position.

The start point is not included in this list.

Return type:

List[Tuple[int, int]]

tdl.map.bresenham(x1, y1, x2, y2)[source]

Return a list of points in a bresenham line.

Implementation hastily copied from RogueBasin.

Returns:
A list of (x, y) points,
including both the start and end-points.
Return type:List[Tuple[int, int]]
tdl.map.quick_fov(x, y, callback, fov='PERMISSIVE', radius=7.5, lightWalls=True, sphere=True)[source]

All field-of-view functionality in one call.

Before using this call be sure to make a function, lambda, or method that takes 2 positional parameters and returns True if light can pass through the tile or False for light-blocking tiles and for indexes that are out of bounds of the dungeon.

This function is ‘quick’ as in no hassle but can quickly become a very slow function call if a large radius is used or the callback provided itself isn’t optimized.

Always check if the index is in bounds both in the callback and in the returned values. These values can go into the negatives as well.

Parameters:
  • x (int) – x center of the field-of-view
  • y (int) – y center of the field-of-view
  • callback (Callable[[int, int], bool]) – This should be a function that takes two positional arguments x,y and returns True if the tile at that position is transparent or False if the tile blocks light or is out of bounds.
  • fov (Text) –

    The type of field-of-view to be used.

    Available types are: ‘BASIC’, ‘DIAMOND’, ‘SHADOW’, ‘RESTRICTIVE’, ‘PERMISSIVE’, ‘PERMISSIVE0’, ‘PERMISSIVE1’, ..., ‘PERMISSIVE8’

  • radius (float) –

    When sphere is True a floating point can be used to fine-tune the range. Otherwise the radius is just rounded up.

    Be careful as a large radius has an exponential affect on how long this function takes.

  • lightWalls (bool) – Include or exclude wall tiles in the field-of-view.
  • sphere (bool) – True for a spherical field-of-view. False for a square one.
Returns:

A set of (x, y) points that are within the

field-of-view.

Return type:

Set[Tuple[int, int]]

tdl.noise

This module provides advanced noise generation.

Noise is sometimes used for over-world generation, height-maps, and cloud/mist/smoke effects among other things.

You can see examples of the available noise algorithms in the libtcod documentation here.

class tdl.noise.Noise(algorithm='PERLIN', mode='FLAT', hurst=0.5, lacunarity=2.0, octaves=4.0, seed=None, dimensions=4)[source]

An advanced noise generator.

Deprecated since version 3.2: This class has been replaced by tcod.noise.Noise.

Parameters:
  • algorithm (Text) –

    The primary noise algorithm to be used.

    Can be one of ‘PERLIN’, ‘SIMPLEX’, ‘WAVELET’

    • ‘PERLIN’ - A popular noise generator.
    • ‘SIMPLEX’ - In theory this is a slightly faster generator with less noticeable directional artifacts.
    • ‘WAVELET’ - A noise generator designed to reduce aliasing and not lose detail when summed into a fractal (as with the ‘FBM’ and ‘TURBULENCE’ modes.) This works faster at higher dimensions.
  • mode (Text) –

    A secondary parameter to determine how noise is generated.

    Can be one of ‘FLAT’, ‘FBM’, ‘TURBULENCE’

    • ‘FLAT’ - Generates the simplest form of noise. This mode does not use the hurst, lacunarity, and octaves parameters.
    • ‘FBM’ - Generates fractal brownian motion.
    • ‘TURBULENCE’ - Generates detailed noise with smoother and more natural transitions.
  • hurst (float) –

    The hurst exponent.

    This describes the raggedness of the resultant noise, with a higher value leading to a smoother noise. It should be in the 0.0-1.0 range.

    This is only used in ‘FBM’ and ‘TURBULENCE’ modes.

  • lacunarity (float) –

    A multiplier that determines how quickly the frequency increases for each successive octave.

    The frequency of each successive octave is equal to the product of the previous octave’s frequency and the lacunarity value.

    This is only used in ‘FBM’ and ‘TURBULENCE’ modes.

  • octaves (float) –

    Controls the amount of detail in the noise.

    This is only used in ‘FBM’ and ‘TURBULENCE’ modes.

  • seed (Hashable) –

    You can use any hashable object to be a seed for the noise generator.

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

get_point(*position)[source]

Return the noise value of a specific position.

Example usage: value = noise.getPoint(x, y, z)

Parameters:position (Tuple[float, ..]) – The point to sample at.
Returns:The noise value at position.
This will be a floating point in the 0.0-1.0 range.
Return type:float