### Main Function Setup with Global Variables Source: https://python-tcod.readthedocs.io/en/stable/_sources/tutorial/part-03.rst.txt Initializes the game console, states, and context, then starts the main game loop. Requires importing necessary modules like 'g', 'game.state_tools', and 'game.states'. ```python import g import game.state_tools import game.states def main() -> None: """Entry point function.""" tileset = tcod.tileset.load_tilesheet( "data/Alloy_curses_12x12.png", columns=16, rows=16, charmap=tcod.tileset.CHARMAP_CP437 ) tcod.tileset.procedural_block_elements(tileset=tileset) g.console = tcod.console.Console(80, 50) g.states = [game.states.MainMenu()] with tcod.context.new(console=g.console, tileset=tileset) as g.context: game.state_tools.main_loop() ``` -------------------------------- ### Pathfinding with SimpleGraph and Pathfinder Source: https://python-tcod.readthedocs.io/en/stable/_modules/tcod/path.html This example demonstrates the basic setup for pathfinding. It involves creating a 2D NumPy array for the map, initializing a SimpleGraph, and then a Pathfinder. Finally, it shows how to add a root and find a path. ```python import numpy as np import tcod.path # Example map: 0 is blocked, other values are movement cost map_array = np.array([ [1, 1, 1, 1, 1], [1, 0, 1, 0, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1], ], dtype=np.int32) # Create a graph from the map array graph = tcod.path.SimpleGraph(map_array) # Create a pathfinder instance pathfinder = tcod.path.Pathfinder(graph) # Set the root node (e.g., player position) pathfinder.add_root((0, 0)) # Get a path from the root to a target path = pathfinder.path_from((3, 4)) print(f"Path found: {path}") # Get a path towards the root from a target path_to_root = pathfinder.path_to((3, 4)) print(f"Path to root: {path_to_root}") ``` -------------------------------- ### Load Tileset and Render Console to SDL Source: https://python-tcod.readthedocs.io/en/stable/_modules/tcod/render.html This example demonstrates loading a tileset, creating a console, printing text, and rendering it to an SDL window. It requires SDL window and renderer setup, and uses `SDLTilesetAtlas` and `SDLConsoleRender` for the rendering process. The loop continuously presents the rendered console and handles window events. ```python tileset = tcod.tileset.load_tilesheet("dejavu16x16_gs_tc.png", 32, 8, tcod.tileset.CHARMAP_TCOD) console = tcod.console.Console(20, 8) console.print(0, 0, "Hello World") sdl_window = tcod.sdl.video.new_window( console.width * tileset.tile_width, console.height * tileset.tile_height, flags=tcod.lib.SDL_WINDOW_RESIZABLE, ) sdl_renderer = tcod.sdl.render.new_renderer(sdl_window, target_textures=True) atlas = tcod.render.SDLTilesetAtlas(sdl_renderer, tileset) console_render = tcod.render.SDLConsoleRender(atlas) while True: sdl_renderer.copy(console_render.render(console)) sdl_renderer.present() for event in tcod.event.wait(): if isinstance(event, tcod.event.Quit): raise SystemExit() ``` -------------------------------- ### Synchronous Audio Playback Example Source: https://python-tcod.readthedocs.io/en/stable/_modules/tcod/sdl/audio.html Demonstrates how to open an audio device, set up separate streams for music and sound effects with different gain levels, load an audio sample using soundfile, queue the audio, and play it back synchronously. Requires the 'soundfile' library to be installed. ```Python import time import soundfile # pip install soundfile import tcod.sdl.audio device = tcod.sdl.get_default_playback().open() # Open the default output device # AudioDevice's can be opened again to form a hierarchy # This can be used to give music and sound effects their own configuration device_music = device.open() device_music.gain = 0 # Mute music device_effects = device.open() device_effects.gain = 10 ** (-6 / 10) # -6dB sound, sample_rate = soundfile.read("example_sound.wav", dtype="float32") # Load an audio sample using SoundFile stream = device_effects.new_stream(format=sound.dtype, frequency=sample_rate, channels=sound.shape[1]) stream.queue_audio(sound) # Play audio by appending it to the audio stream stream.flush() while stream.queued_samples: # Wait until stream is finished time.sleep(0.001) ``` -------------------------------- ### Initialize Root Console Source: https://python-tcod.readthedocs.io/en/stable/_modules/tcod/libtcodpy.html Sets up the primary display window for the application. This function is deprecated and users should refer to the Getting Started documentation for modern context-based initialization. ```python import tcod # Example usage (deprecated): # root_console = tcod.libtcodpy.console_init_root(80, 50, title="My Game", fullscreen=False) ``` -------------------------------- ### Basic Mixer Example Source: https://python-tcod.readthedocs.io/en/stable/sdl/audio.html Demonstrates how to use the BasicMixer to load and play a sound file. Requires the 'soundfile' library. The sound is converted to the device's format and played asynchronously. The example waits for playback to complete. ```python import time import soundfile # pip install soundfile import tcod.sdl.audio device = tcod.sdl.audio.get_default_playback().open() mixer = tcod.sdl.audio.BasicMixer(device) # Setup BasicMixer with the default audio output sound, sample_rate = soundfile.read("example_sound.wav") # Load an audio sample using SoundFile sound = mixer.device.convert(sound, sample_rate) # Convert this sample to the format expected by the device channel = mixer.play(sound) # Start asynchronous playback, audio is mixed on a separate Python thread while channel.busy: # Wait until the sample is done playing time.sleep(0.001) ``` -------------------------------- ### Pathfinder Basic Usage Source: https://python-tcod.readthedocs.io/en/stable/_modules/tcod/path.html Demonstrates basic pathfinding with a SimpleGraph, including adding roots and finding paths. Shows how to get the full path or exclude the starting point. ```python import tcod.path import numpy as np cost = np.ones((5, 5), dtype=np.int8) cost[:, 3:] = 0 graph = tcod.path.SimpleGraph(cost=cost, cardinal=2, diagonal=3) pf = tcod.path.Pathfinder(graph) pf.add_root((0, 0)) print(pf.path_from((2, 2)).tolist()) print(pf.path_from((2, 2))[1:].tolist()) # Exclude the starting point by slicing the array. print(pf.path_from((4, 4)).tolist()) # Blocked paths will only have the index point. print(pf.path_from((4, 4))[1:].tolist()) # Exclude the starting point so that a blocked path is an empty list. ``` -------------------------------- ### Initialize and Get Joystick Properties Source: https://python-tcod.readthedocs.io/en/stable/_modules/tcod/sdl/joystick.html This snippet demonstrates how to open a joystick by its instance ID and retrieve its properties such as name, number of axes, buttons, hats, and trackballs. It also shows how to get the joystick's unique GUID and instance ID. ```python from tcod.sdl.joystick import Joystick # Assuming instance_id is known instance_id = 0 # Replace with actual instance ID joystick = Joystick._open(instance_id) print(f"Joystick Name: {joystick.name}") print(f"Number of Axes: {joystick.axes}") print(f"Number of Buttons: {joystick.buttons}") print(f"Number of Hats: {joystick.hats}") print(f"Number of Trackballs: {joystick.balls}") print(f"Joystick GUID: {joystick.guid}") print(f"Joystick ID: {joystick.id}") ``` -------------------------------- ### Install Dependencies on Linux (Debian-based) Source: https://python-tcod.readthedocs.io/en/stable/_sources/installation.rst.txt Install necessary build tools and development libraries for python-tcod on Debian-based Linux systems using apt. ```bash sudo apt install build-essential python3-dev python3-pip python3-numpy libsdl2-dev libffi-dev ``` -------------------------------- ### Joystick Device Addition/Removal Example Source: https://python-tcod.readthedocs.io/en/stable/_modules/tcod/event.html Manage a set of connected joysticks. This example demonstrates how to add new joysticks when they are detected and remove them when disconnected. ```python joysticks: set[tcod.sdl.joystick.Joystick] = {} for event in tcod.event.get(): match event: case tcod.event.JoystickDevice(type="JOYDEVICEADDED", joystick=new_joystick): joysticks.add(new_joystick) case tcod.event.JoystickDevice(type="JOYDEVICEREMOVED", joystick=joystick): joysticks.remove(joystick) ``` -------------------------------- ### Overlapping Endpoints Example Source: https://python-tcod.readthedocs.io/en/stable/_modules/tcod/path.html Shows that when start and end points are the same, a single step path is returned. ```python >>> tcod.path.path2d(cost, start_points=[(0, 0)], end_points=[(0, 0)], cardinal=70, diagonal=99) array([[0, 0]], dtype=int32) ``` -------------------------------- ### Get AStar Path Origin Source: https://python-tcod.readthedocs.io/en/stable/_modules/tcod/libtcodpy.html Retrieves the starting coordinates of a computed AStar path. This point updates as the path is traversed. ```python x = ffi.new("int *") y = ffi.new("int *") lib.TCOD_path_get_origin(p._path_c, x, y) return x[0], y[0] ``` -------------------------------- ### Get Elapsed Seconds Source: https://python-tcod.readthedocs.io/en/stable/_modules/tcod/libtcodpy.html Returns the number of seconds that have passed since the program started. Deprecated; use Python's 'time' module. ```python import tcod elapsed_sec = tcod.sys_elapsed_seconds() ``` -------------------------------- ### SimpleGraph Initialization and Pathfinding Example Source: https://python-tcod.readthedocs.io/en/stable/_modules/tcod/path.html Demonstrates how to create a SimpleGraph with custom costs and use a Pathfinder to find a path between two points. The 'greed' parameter influences the heuristic's accuracy and speed. ```python >>> import numpy as np >>> import tcod >>> cost = np.ones((5, 10), dtype=np.int8, order="F") >>> graph = tcod.path.SimpleGraph(cost=cost, cardinal=2, diagonal=3) >>> pf = tcod.path.Pathfinder(graph) >>> pf.add_root((2, 4)) >>> pf.path_to((3, 7)).tolist() [[2, 4], [2, 5], [2, 6], [3, 7]] ``` -------------------------------- ### Get Elapsed Milliseconds Source: https://python-tcod.readthedocs.io/en/stable/_modules/tcod/libtcodpy.html Returns the number of milliseconds that have passed since the program started. Deprecated; use Python's 'time' module. ```python import tcod elapsed_ms = tcod.sys_elapsed_milli() ``` -------------------------------- ### Initialize and Run Basic Event Loop Source: https://python-tcod.readthedocs.io/en/stable/tutorial/part-01.html This snippet demonstrates how to set up a console, load a tileset, and enter a main loop that presents the console and handles events. It's used to display 'Hello World' and keep the window open until the user quits. ```python from __future__ import annotations import tcod.console import tcod.context import tcod.event import tcod.tileset def main() -> None: """Show "Hello World" until the window is closed.""" tileset = tcod.tileset.load_tilesheet( "data/Alloy_curses_12x12.png", columns=16, rows=16, charmap=tcod.tileset.CHARMAP_CP437 ) tcod.tileset.procedural_block_elements(tileset=tileset) console = tcod.console.Console(80, 50) console.print(0, 0, "Hello World") # Test text by printing "Hello World" to the console with tcod.context.new(console=console, tileset=tileset) as context: while True: # Main loop context.present(console) # Render the console to the window and show it for event in tcod.event.wait(): # Event loop, blocks until pending events exist print(event) if isinstance(event, tcod.event.Quit): raise SystemExit if __name__ == "__main__": main() ``` -------------------------------- ### AStar Get Path Source: https://python-tcod.readthedocs.io/en/stable/_modules/tcod/path.html Calculates and returns a path from a start to a goal coordinate using the A* algorithm. Returns an empty list if no path is found. ```python def get_path(self, start_x: int, start_y: int, goal_x: int, goal_y: int) -> list[tuple[int, int]]: """Return a list of (x, y) steps to reach the goal point, if possible. Args: start_x (int): Starting X position. start_y (int): Starting Y position. goal_x (int): Destination X position. goal_y (int): Destination Y position. ``` -------------------------------- ### Initialize Root Console with Context Manager Source: https://python-tcod.readthedocs.io/en/stable/libtcodpy.html This example demonstrates initializing the root console using a context manager, ensuring the window is properly closed after the game loop. Vsync is enabled for smoother rendering. ```python with libtcodpy.console_init_root(80, 50, vsync=True) as root_console: ... # Put your game loop here. ... # Window closes at the end of the above block. ``` -------------------------------- ### Unreachable Endpoints Example Source: https://python-tcod.readthedocs.io/en/stable/_modules/tcod/path.html Demonstrates how unreachable endpoints result in an empty path array. This applies when start and end points are in disconnected areas of the cost map. ```python >>> tcod.path.path2d(cost, start_points=[(0, 0)], end_points=[(3, 6)], cardinal=70, diagonal=99) array([], shape=(0, 2), dtype=int...) ``` ```python >>> tcod.path.path2d(cost, start_points=[(0, 0), (3, 0)], end_points=[(0, 6), (3, 6)], cardinal=70, diagonal=99) array([], shape=(0, 2), dtype=int...) ``` ```python >>> tcod.path.path2d(cost, start_points=[], end_points=[], cardinal=70, diagonal=99) array([], shape=(0, 2), dtype=int...) ``` -------------------------------- ### Synchronous Audio Playback Example Source: https://python-tcod.readthedocs.io/en/stable/sdl/audio.html Demonstrates synchronous audio playback using tcod.sdl.audio and soundfile. It shows how to open audio devices, set gain levels for different audio types (music and effects), load a sound sample, queue it for playback, and wait for it to finish. ```python # Synchronous audio example import time import soundfile # pip install soundfile import tcod.sdl.audio device = tcod.sdl.get_default_playback().open() # Open the default output device # AudioDevice's can be opened again to form a hierarchy # This can be used to give music and sound effects their own configuration device_music = device.open() device_music.gain = 0 # Mute music device_effects = device.open() device_effects.gain = 10 ** (-6 / 10) # -6dB sound, sample_rate = soundfile.read("example_sound.wav", dtype="float32") # Load an audio sample using SoundFile stream = device_effects.new_stream(format=sound.dtype, frequency=sample_rate, channels=sound.shape[1]) stream.queue_audio(sound) # Play audio by appending it to the audio stream stream.flush() while stream.queued_samples: time.sleep(0.001) ``` -------------------------------- ### SimpleGraph Pathfinder Example Source: https://python-tcod.readthedocs.io/en/stable/_modules/tcod/path.html Demonstrates creating a SimpleGraph and Pathfinder, setting roots, and finding paths. ```python import tcod.path import numpy as np graph = tcod.path.SimpleGraph( cost=np.ones((5, 5), np.int8), cardinal=2, diagonal=3, ) pf = tcod.path.Pathfinder(graph) pf.distance[:, 0] = 0 # Set roots along entire left edge pf.rebuild_frontier() print(pf.path_to((0, 2)).tolist()) print(pf.path_to((4, 2)).tolist()) ``` -------------------------------- ### Render a console to an SDL Texture Source: https://python-tcod.readthedocs.io/en/stable/tcod/render.html This example demonstrates how to load a tileset, create a console, and render it to an SDL window. It sets up an SDL renderer and a tileset atlas for efficient rendering. The loop continuously renders the console and presents it, handling window events. ```python tileset = tcod.tileset.load_tilesheet("dejavu16x16_gs_tc.png", 32, 8, tcod.tileset.CHARMAP_TCOD) console = tcod.console.Console(20, 8) console.print(0, 0, "Hello World") sdl_window = tcod.sdl.video.new_window( console.width * tileset.tile_width, console.height * tileset.tile_height, flags=tcod.lib.SDL_WINDOW_RESIZABLE, ) sdl_renderer = tcod.sdl.render.new_renderer(sdl_window, target_textures=True) atlas = tcod.render.SDLTilesetAtlas(sdl_renderer, tileset) console_render = tcod.render.SDLConsoleRender(atlas) while True: sdl_renderer.copy(console_render.render(console)) sdl_renderer.present() for event in tcod.event.wait(): if isinstance(event, tcod.event.Quit): raise SystemExit() ``` -------------------------------- ### Get NumPy index array for a line Source: https://python-tcod.readthedocs.io/en/stable/_modules/tcod/libtcodpy.html Returns NumPy index arrays (i, j) for points along a Bresenham line. The start point is included by default, but can be excluded with `inclusive=False`. This function is deprecated and replaced by `tcod.los.bresenham`. ```python array = tcod.los.bresenham((x1, y1), (x2, y2)).T if not inclusive: array = array[:, 1:] i, j = array return i, j ``` -------------------------------- ### Dynamically-Sized Console Hello World Source: https://python-tcod.readthedocs.io/en/stable/tcod/getting-started.html An example demonstrating a maximized window with a dynamically scaled console that resizes with the window. Uses a fallback font if not specified, which is not recommended for release. The integer_scaling parameter prevents slight stretching. ```python #!/usr/bin/env python import tcod.context import tcod.event WIDTH, HEIGHT = 720, 480 # Window pixel resolution (when not maximized.) FLAGS = tcod.context.SDL_WINDOW_RESIZABLE | tcod.context.SDL_WINDOW_MAXIMIZED def main() -> None: """Script entry point.""" with tcod.context.new( # New window with pixel resolution of width×height. width=WIDTH, height=HEIGHT, sdl_window_flags=FLAGS ) as context: while True: console = context.new_console() # Console size based on window resolution and tile size. console.print(0, 0, "Hello World") context.present(console, integer_scaling=True) for event in tcod.event.wait(): event = context.convert_event(event) # Sets tile coordinates for mouse events. print(event) # Print event names and attributes. match event: case tcod.event.Quit(): raise SystemExit case tcod.event.WindowResized(width=width, height=height): # Size in pixels pass # The next call to context.new_console may return a different size. if __name__ == "__main__": main() ``` -------------------------------- ### Basic Python Script with Type Hinting Source: https://python-tcod.readthedocs.io/en/stable/_sources/tutorial/part-00.rst.txt This script demonstrates a standard Python entry point with type hinting and a main function. It's designed to be run directly and prints 'Hello World!'. ```python from __future__ import annotations def main() -> None: print("Hello World!") if __name__ == "__main__": main() ``` -------------------------------- ### Create and Inspect a Tileset Source: https://python-tcod.readthedocs.io/en/stable/_modules/tcod/tileset.html Demonstrates creating a basic tileset, adding procedural block elements, and retrieving specific tile data. Shows how to access the alpha channel of a tile. ```python import tcod.tileset tileset = tcod.tileset.Tileset(8, 8) tileset += tcod.tileset.procedural_block_elements(shape=tileset.tile_shape) tileset.get_tile(0x259E)[:, :, 3] # "▞" Quadrant upper right and lower left. ``` ```python array([[ 0, 0, 0, 0, 255, 255, 255, 255], [ 0, 0, 0, 0, 255, 255, 255, 255], [ 0, 0, 0, 0, 255, 255, 255, 255], [ 0, 0, 0, 0, 255, 255, 255, 255], [255, 255, 255, 255, 0, 0, 0, 0], [255, 255, 255, 255, 0, 0, 0, 0], [255, 255, 255, 255, 0, 0, 0, 0], [255, 255, 255, 255, 0, 0, 0, 0]], dtype=uint8) ``` ```python tileset.get_tile(0x2581)[:, :, 3] # "▁" Lower one eighth block. ``` ```python array([[ 0, 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, 0, 0], [255, 255, 255, 255, 255, 255, 255, 255]], dtype=uint8) ``` ```python tileset.get_tile(0x258D)[:, :, 3] # "▍" Left three eighths block. ``` ```python array([[255, 255, 255, 0, 0, 0, 0, 0], [255, 255, 255, 0, 0, 0, 0, 0], [255, 255, 255, 0, 0, 0, 0, 0], [255, 255, 255, 0, 0, 0, 0, 0], [255, 255, 255, 0, 0, 0, 0, 0], [255, 255, 255, 0, 0, 0, 0, 0], [255, 255, 255, 0, 0, 0, 0, 0], [255, 255, 255, 0, 0, 0, 0, 0]], dtype=uint8) ``` -------------------------------- ### Install python-tcod on macOS Source: https://python-tcod.readthedocs.io/en/stable/_sources/installation.rst.txt Install python-tcod using pip in a user environment on macOS. Ensure Python 3 is installed first. ```bash python3 -m pip install --user tcod ``` -------------------------------- ### Basic "Hello World" Window Source: https://python-tcod.readthedocs.io/en/stable/_sources/tutorial/part-01.rst.txt Creates a window and displays "Hello World" until the user closes it. Handles window events and presents the console. ```python def main() -> None: """Show "Hello World" until the window is closed.""" tileset = tcod.tileset.load_tilesheet( "data/Alloy_curses_12x12.png", columns=16, rows=16, charmap=tcod.tileset.CHARMAP_CP437 ) tcod.tileset.procedural_block_elements(tileset=tileset) console = tcod.console.Console(80, 50) console.print(0, 0, "Hello World") # Test text by printing "Hello World" to the console with tcod.context.new(console=console, tileset=tileset) as context: while True: # Main loop context.present(console) # Render the console to the window and show it for event in tcod.event.wait(): # Event loop, blocks until pending events exist print(event) if isinstance(event, tcod.event.Quit): raise SystemExit if __name__ == "__main__": main() ``` -------------------------------- ### Example libtcodpy project structure Source: https://python-tcod.readthedocs.io/en/stable/installation.html This shows the typical file structure of a project using the older libtcodpy library. ```text libtcodpy/ (or libtcodpy.py) libtcod.dll (or libtcod-mingw.dll) SDL2.dll (or SDL.dll) ``` -------------------------------- ### Verify Python Installation (Windows) Source: https://python-tcod.readthedocs.io/en/stable/_sources/installation.rst.txt Check if Python is installed and accessible from the command line. Ensure the version matches your installed Python. ```bash >python -V Python 3.10.0 ``` ```bash >pip -V pip 21.2.4 from ...\Python310\lib\site-packages\pip (python 3.10) ``` -------------------------------- ### Configure Event Loop and Basic Event Handling Source: https://python-tcod.readthedocs.io/en/stable/_sources/tutorial/part-01.rst.txt Sets up a game loop that keeps the window open, displays a console with 'Hello World', and handles window close events. Events are printed to the console output for inspection. ```python from __future__ import annotations import tcod.console import tcod.context import tcod.event import tcod.tileset def main() -> None: """Load a tileset and open a window using it, this window will immediately close.""" tileset = tcod.tileset.load_tilesheet( "data/Alloy_curses_12x12.png", columns=16, rows=16, charmap=tcod.tileset.CHARMAP_CP437 ) tcod.tileset.procedural_block_elements(tileset=tileset) console = tcod.console.Console(columns=80, rows=50) with tcod.context.new(columns=80, rows=50, tileset=tileset) as context: while True: console.print(x=0, y=0, string="Hello World") context.present(console) for event in tcod.event.wait(): print(event) if isinstance(event, tcod.event.Quit): raise SystemExit if __name__ == "__main__": main() ``` -------------------------------- ### Verify Pip Installation Source: https://python-tcod.readthedocs.io/en/stable/installation.html Run this command in your terminal to check your pip version and its associated Python installation. Ensure it matches your installed version. ```bash >pip -V pip 21.2.4 from ...\Python310\lib\site-packages\pip (python 3.10) ``` -------------------------------- ### Window.start_text_input Source: https://python-tcod.readthedocs.io/en/stable/sdl/video.html Starts receiving text events for the window and can enable an on-screen keyboard. ```APIDOC ## Window.start_text_input ### Description Starts receiving text events for the window and can enable an on-screen keyboard. ### Parameters * **type** – Type of text being inputted, see `TextInputType`. * **capitalization** – Capitalization hint, default is based on type given, see `Capitalization`. * **autocorrect** – Enable auto completion and auto correction. * **multiline** – Allow multiple lines of text. * **android_type** – Input type for Android, see SDL docs. ### See Also * `stop_text_input` * `set_text_input_area` * `TextInput` * https://wiki.libsdl.org/SDL3/SDL_StartTextInputWithProperties ### Added in version 19.1. ``` -------------------------------- ### Install python-tcod on Windows Source: https://python-tcod.readthedocs.io/en/stable/_sources/installation.rst.txt Use pip to install the python-tcod library from a Windows command line. Add the --user flag if Python was installed for all users. ```bash >pip install tcod ``` -------------------------------- ### Install tcod via PyCharm Terminal Source: https://python-tcod.readthedocs.io/en/stable/_sources/faq.rst.txt Alternatively, install tcod directly into your PyCharm project's virtual environment by running 'pip install tcod' in the integrated terminal. Ensure you are in the correct project environment. ```bash pip install tcod ``` -------------------------------- ### Example: Check and Allow Screen Saver Source: https://python-tcod.readthedocs.io/en/stable/_modules/tcod/sdl/video.html Demonstrates how to check the current screen saver status and then allow it. This is generally not recommended unless specific conditions are met. ```python import tcod.sdl.video print(f"Screen saver was allowed: {tcod.sdl.video.screen_saver_allowed()}") # Allow the screen saver. # Might be okay for some turn-based games which don't use a gamepad. tcod.sdl.video.screen_saver_allowed(True) ``` -------------------------------- ### BasicMixer Initialization and Usage Source: https://python-tcod.readthedocs.io/en/stable/_modules/tcod/sdl/audio.html Sets up a BasicMixer with a default audio device, loads a sound file, converts it to the device's format, and plays it asynchronously. Waits for playback to complete. ```Python import time import soundfile # pip install soundfile import tcod.sdl.audio device = tcod.sdl.audio.get_default_playback().open() mixer = tcod.sdl.audio.BasicMixer(device) # Setup BasicMixer with the default audio output sound, sample_rate = soundfile.read("example_sound.wav") # Load an audio sample using SoundFile sound = mixer.device.convert(sound, sample_rate) # Convert this sample to the format expected by the device channel = mixer.play(sound) # Start asynchronous playback, audio is mixed on a separate Python thread while channel.busy: # Wait until the sample is done playing time.sleep(0.001) ``` -------------------------------- ### Get Mouse Status (Deprecated) Source: https://python-tcod.readthedocs.io/en/stable/_modules/tcod/libtcodpy.html This function is deprecated. Use `tcod.event.get_mouse_state()` to get the current mouse state. ```python import tcod def mouse_get_status() -> Mouse: return Mouse(lib.TCOD_mouse_get_status()) ``` -------------------------------- ### Presenting a Console with Options Source: https://python-tcod.readthedocs.io/en/stable/_modules/tcod/context.html Use the `present` method to display a console on the screen. You can control aspect ratio, scaling, clear color, and alignment. ```python context.present( console, keep_aspect=False, integer_scaling=False, clear_color=(0, 0, 0), align=(0.5, 0.5), ) ``` -------------------------------- ### Check 'Start' Button State Source: https://python-tcod.readthedocs.io/en/stable/_modules/tcod/sdl/joystick.html Returns True if the 'Start' button is currently held down, False otherwise. ```python @property def _start(self) -> bool: """Return True if this button is held.""" return bool(lib.SDL_GetGamepadButton(self.sdl_controller_p, lib.SDL_GAMEPAD_BUTTON_START)) ``` -------------------------------- ### Traversing a BSP Tree in Python Source: https://python-tcod.readthedocs.io/en/stable/tcod/bsp.html Demonstrates how to initialize a BSP tree, split it recursively, and then traverse the resulting nodes using a pre-order traversal. Assumes custom room creation and connection logic. ```python import tcod.bsp 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, ) # In pre order, leaf nodes are visited before the nodes that connect them. for node in bsp.pre_order(): if node.children: node1, node2 = node.children print('Connect the rooms:\n%s\n%s' % (node1, node2)) else: print('Dig a room for %s.' % node) ``` -------------------------------- ### tcod.path.path2d Source: https://python-tcod.readthedocs.io/en/stable/tcod/path.html Calculates a path between specified start and end points on a grid with given movement costs. It functions as A* if one start and one end point are provided, and as Dijkstra's algorithm if multiple start or end points are given. ```APIDOC ## tcod.path.path2d ### Description Calculates a path between specified start and end points on a grid with given movement costs. It functions as A* if one start and one end point are provided, and as Dijkstra's algorithm if multiple start or end points are given. ### Method `path2d` ### Parameters #### Path Parameters - **_cost** (ArrayLike) - Required - A 2D array of integers representing the cost of traversing each node. - **_start_points** (Sequence[tuple[int, int]]) - Required - A sequence of one or more starting points (x, y) indexing the cost array. - **_end_points** (Sequence[tuple[int, int]]) - Required - A sequence of one or more ending points (x, y) indexing the cost array. - **_cardinal** (int) - Required - The cost associated with moving in a cardinal direction (up, down, left, right). - **_diagonal** (int | None) - Optional - The cost associated with moving in a diagonal direction. If None or 0, diagonal movement is disabled. - **_check_bounds** (bool) - Optional - If True (default), out-of-bounds points will raise an `IndexError`. If False, they are silently ignored. ### Returns - **NDArray[np.intc]** - A 2D NumPy array representing the shortest path found between the start and end points. ``` -------------------------------- ### Verify Python Installation Source: https://python-tcod.readthedocs.io/en/stable/installation.html Run this command in your terminal to check your Python version. Ensure it matches your installed version. ```bash >python -V Python 3.10.0 ``` -------------------------------- ### Loading Tileset and Opening Window Source: https://python-tcod.readthedocs.io/en/stable/tutorial/part-01.html This snippet demonstrates how to load a tileset image and initialize a tcod context to open a window. Ensure the tileset image is in the correct 'data/' directory and 'tcod' is installed. ```python from __future__ import annotations import tcod.context # Add these imports import tcod.tileset def main() -> None: """Load a tileset and open a window using it, this window will immediately close.""" tileset = tcod.tileset.load_tilesheet( "data/Alloy_curses_12x12.png", columns=16, rows=16, charmap=tcod.tileset.CHARMAP_CP437 ) tcod.tileset.procedural_block_elements(tileset=tileset) with tcod.context.new(tileset=tileset) as context: pass # The window will stay open for the duration of this block if __name__ == "__main__": main() ``` -------------------------------- ### new_window Source: https://python-tcod.readthedocs.io/en/stable/_modules/tcod/sdl/video.html Initialize and return a new SDL Window. ```APIDOC ## new_window ### Description Initialize and return a new SDL Window. ### Method This is a function within the `tcod.sdl.video` module. ### Parameters #### Parameters - **width** (int) - Required - The requested pixel width of the window. - **height** (int) - Required - The requested pixel height of the window. - **x** (int | None) - Optional - The left-most position of the window. - **y** (int | None) - Optional - The top-most position of the window. - **title** (str | None) - Optional - The title text of the new window. If no option is given then `sys.arg[0]` will be used as the title. - **flags** (int) - Optional - The SDL flags to use for this window, such as `tcod.sdl.video.WindowFlags.RESIZABLE`. See :any:`WindowFlags` for more options. Defaults to `0`. ### Response - **Window** - A new SDL Window object. ### Example ```python import tcod.sdl.video # Create a new resizable window with a custom title. window = tcod.sdl.video.new_window(640, 480, title="Title bar text", flags=tcod.sdl.video.WindowFlags.RESIZABLE) ``` ``` -------------------------------- ### Check 'Guide' Button State Source: https://python-tcod.readthedocs.io/en/stable/_modules/tcod/sdl/joystick.html Returns True if the 'Guide' button (often the system or home button) is currently held down, False otherwise. ```python @property def _guide(self) -> bool: """Return True if this button is held.""" return bool(lib.SDL_GetGamepadButton(self.sdl_controller_p, lib.SDL_GAMEPAD_BUTTON_GUIDE)) ``` -------------------------------- ### open Source: https://python-tcod.readthedocs.io/en/stable/sdl/audio.html Opens an audio device for playback or capture with specified settings and returns the `AudioDevice` object. ```APIDOC ## open ### Description Open an audio device for playback or capture and return it. ### Method `tcod.sdl.audio.open` ### Parameters * **_name** (str | None) - The name of the audio device to open. If None, the default device is used. * **capture** (bool) - If True, opens the device for audio capture (recording). Defaults to False. * **frequency** (int) - The desired sample rate in Hz. Defaults to 44100. * **format** (DTypeLike) - The desired audio data format. Defaults to `np.float32`. * **channels** (int) - The desired number of audio channels. Defaults to 2. * **samples** (int) - The desired number of samples per audio buffer. Defaults to 0 (system default). * **allowed_changes** (AllowedChanges) - Specifies which audio device parameters can be changed. Defaults to `AllowedChanges.NONE`. * **paused** (bool) - If True, the device will be opened in a paused state. Defaults to False. * **callback** (None | Literal[True] | Callable[[AudioDevice, NDArray[Any]], None]) - A callback function to be executed when audio data is ready for playback or capture. If `True`, a default callback is used. ### Response * **AudioDevice** - The opened `AudioDevice` object. ``` -------------------------------- ### Install python-tcod 6.0.7 on Python 2.7 Source: https://python-tcod.readthedocs.io/en/stable/installation.html Use this command to install a specific version of python-tcod for Python 2.7 environments. Note that Python 2 is no longer supported. ```bash python2 -m pip install tcod==6.0.7 ``` -------------------------------- ### Create and Split a BSP Tree Source: https://python-tcod.readthedocs.io/en/stable/_modules/tcod/bsp.html Demonstrates how to initialize a BSP tree and recursively split it into smaller nodes. This is a foundational step for dungeon generation using BSP. ```python import tcod.bsp 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, ) ``` -------------------------------- ### Install python-tcod for Python 2.7 Source: https://python-tcod.readthedocs.io/en/stable/_sources/installation.rst.txt Use this command to install a specific version of python-tcod compatible with Python 2.7. Ensure you are using Python 2.7 before running this command. ```bash python2 -m pip install tcod==6.0.7 ``` -------------------------------- ### Console Initialization Source: https://python-tcod.readthedocs.io/en/stable/_modules/tcod/console.html Initializes a new console with specified dimensions and optional buffer. It sets up the internal tile data and default rendering properties. ```APIDOC ## Console Initialization ### Description Initializes a new console with specified dimensions and optional buffer. It sets up the internal tile data and default rendering properties. ### Method __init__ ### Parameters - **width** (int) - Required - The width of the console. - **height** (int) - Required - The height of the console. - **order** (Literal["C", "F"]) - Optional - The memory order of the console buffer ('C' for C-style, 'F' for Fortran-style). Defaults to 'C'. - **buffer** (NDArray[Any] | None) - Optional - An existing NumPy array to use as the console buffer. If None, a new buffer is created. ``` -------------------------------- ### Get available audio capture devices Source: https://python-tcod.readthedocs.io/en/stable/_modules/tcod/sdl/audio.html Use `get_capture_devices` to get a dictionary of all available audio input (recording) devices. Device names map to `AudioDevice` objects. ```python tcod.sdl.sys.init(tcod.sdl.sys.Subsystem.AUDIO) count = ffi.new("int[1]") devices_array = ffi.gc(lib.SDL_GetAudioRecordingDevices(count), lib.SDL_free) return { device.name: device for device in (AudioDevice(ffi.cast("SDL_AudioDeviceID", p)) for p in devices_array[0 : count[0]]) } ``` -------------------------------- ### Map Class Initialization and Basic Usage Source: https://python-tcod.readthedocs.io/en/stable/_modules/tcod/map.html Demonstrates how to create a tcod.map.Map instance and access its basic attributes like 'walkable'. Shows how to modify 'transparent' cells and how the 'fov' attribute is updated after computing field-of-view. ```python >>> import tcod >>> m = tcod.map.Map(width=3, height=4) >>> m.walkable array([[False, False, False], [False, False, False], [False, False, False], [False, False, False]]...) # 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]]...) >>> m.compute_fov(0, 0) >>> m.fov array([[ True, True, True], [ True, True, True], [False, True, True], [False, False, True]]...) >>> m.fov.item(3, 1) False ``` -------------------------------- ### Install python-tcod dependencies on Linux (Debian-based) Source: https://python-tcod.readthedocs.io/en/stable/installation.html Installs necessary build dependencies for python-tcod on Debian-based Linux systems using apt. Ensure your GCC and SDL versions meet the requirements. ```bash sudo apt install build-essential python3-dev python3-pip python3-numpy libsdl2-dev libffi-dev ``` -------------------------------- ### Initializing Console with Tile Graphics Source: https://python-tcod.readthedocs.io/en/stable/tcod/console.html Shows how to initialize a tcod console and populate its RGB data using a tile graphics lookup table. This example demonstrates converting a 2D array of tile indices into actual tile graphics for display. ```python >>> 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) <###### #.^..# #..~~# #..~~# ######> ``` -------------------------------- ### Setup console data from C buffer Source: https://python-tcod.readthedocs.io/en/stable/_modules/tcod/console.html Internal method to set up NumPy arrays over libtcod data buffers. It handles both root and non-root console data. ```python def _init_setup_console_data(self, order: Literal["C", "F"] = "C") -> None: """Setup numpy arrays over libtcod data buffers.""" global _root_console # noqa: PLW0603 self._key_color = None if self.console_c == ffi.NULL: _root_console = self self._console_data = lib.TCOD_ctx.root else: self._console_data = ffi.cast("struct TCOD_Console*", self.console_c) self._tiles = np.frombuffer( ffi.buffer(self._console_data.tiles[0 : self.width * self.height]), dtype=self.DTYPE, ).reshape((self.height, self.width)) self._order = tcod._internal.verify_order(order) ``` -------------------------------- ### Console Class Dtype Initialization Example Source: https://python-tcod.readthedocs.io/en/stable/_modules/tcod/console.html Demonstrates how to create a NumPy buffer with the `Console.DTYPE` and initialize a `tcod.console.Console` object from it. This example shows setting characters and using the 'F' order for indexing. ```python 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) ``` -------------------------------- ### Initialize and Open Game Controller Source: https://python-tcod.readthedocs.io/en/stable/_modules/tcod/sdl/joystick.html This snippet shows how to open a game controller by its instance ID and access its associated joystick object. It also demonstrates how to keep the controller's underlying SDL object alive. ```python from tcod.sdl.joystick import GameController # Assuming instance_id is known instance_id = 0 # Replace with actual instance ID game_controller = GameController._open(instance_id) print(f"Game Controller Joystick ID: {game_controller.joystick.id}") ``` -------------------------------- ### Install tcod in PyCharm Virtual Environment Source: https://python-tcod.readthedocs.io/en/stable/_sources/faq.rst.txt Use a requirements.txt file to specify the tcod package for installation within your PyCharm project's virtual environment. This ensures the library is available to your project. ```python # requirements.txt # https://pip.pypa.io/en/stable/cli/pip_install/#requirements-file-format tcod ```