### Fixed-size Console Example Source: https://github.com/libtcod/python-tcod/blob/main/docs/tcod/getting-started.md A 'Hello World' script demonstrating fixed-size console setup, font loading, window context, and event handling. Requires a specific font file ('dejavu10x10_gs_tc.png') in the script's directory. ```python #!/usr/bin/env python # Make sure 'dejavu10x10_gs_tc.png' is in the same directory as this script. import tcod.console import tcod.context import tcod.event import tcod.tileset WIDTH, HEIGHT = 80, 60 # Console width and height in tiles. def main() -> None: """Script entry point.""" # Load the font, a 32 by 8 tile font with libtcod's old character layout. tileset = tcod.tileset.load_tilesheet( "dejavu10x10_gs_tc.png", 32, 8, tcod.tileset.CHARMAP_TCOD, ) # Create the main console. console = tcod.console.Console(WIDTH, HEIGHT) # Create a window based on this console and tileset. with tcod.context.new( # New window for a console of size columnsĂ—rows. columns=console.width, rows=console.height, tileset=tileset, ) as context: while True: # Main loop, runs until SystemExit is raised. console.clear() console.print(x=0, y=0, text="Hello World!") context.present(console) # Show the console. # This event loop will wait until at least one event is processed before exiting. # For a non-blocking event loop replace `tcod.event.wait` with `tcod.event.get`. for event in tcod.event.wait(): 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 # The window will be closed after the above with-block exits. if __name__ == "__main__": main() ``` -------------------------------- ### Install and Setup Pre-commit Hooks Source: https://github.com/libtcod/python-tcod/blob/main/CONTRIBUTING.md Install the pre-commit package and set up the git pre-commit hook to enforce code styles automatically. This should be done before making any code changes. ```sh pip install pre-commit pre-commit install ``` -------------------------------- ### Install Dependencies and Build Executable Source: https://github.com/libtcod/python-tcod/blob/main/examples/distribution/cx_Freeze/README.rst Install required packages from requirements.txt and then build the project using setup.py. An executable package will be created in the build directory. ```bash pip install -r requirements.txt python setup.py build ``` -------------------------------- ### Verify Python Installation Source: https://github.com/libtcod/python-tcod/blob/main/docs/installation.md Run these commands in your terminal to check your Python and pip installation versions. Ensure the versions match 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) ``` -------------------------------- ### Install Dependencies Source: https://github.com/libtcod/python-tcod/blob/main/examples/distribution/PyInstaller/README.rst Install required packages including tcod, PyInstaller, and pypiwin32 (if on Windows) from requirements.txt. ```bash pip install -r requirements.txt ``` -------------------------------- ### Install Xcode Command Line Tools on MacOS Source: https://github.com/libtcod/python-tcod/blob/main/CONTRIBUTING.md Install the necessary Xcode command line tools on MacOS. This is a prerequisite for building C extensions. ```sh xcode-select --install ``` -------------------------------- ### Install Dependencies on Linux (Debian-based) Source: https://github.com/libtcod/python-tcod/blob/main/docs/installation.md Installs necessary build dependencies for python-tcod on Debian-based Linux distributions using apt. ```bash sudo apt install build-essential python3-dev python3-pip python3-numpy libsdl2-dev libffi-dev ``` -------------------------------- ### Install python-tcod using pip Source: https://github.com/libtcod/python-tcod/blob/main/docs/installation.md Execute this command in a Windows command line to install the python-tcod library. You might need to add the `--user` flag if Python was installed for all users. ```bash >pip install tcod ``` -------------------------------- ### Dynamically-sized Console Example Source: https://github.com/libtcod/python-tcod/blob/main/docs/tcod/getting-started.md Demonstrates creating a maximized window with a dynamically scaled console that resizes with the window. Uses a fallback OS-dependent font and integer scaling to prevent 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() ``` -------------------------------- ### Install python-tcod on MacOS Source: https://github.com/libtcod/python-tcod/blob/main/docs/installation.md Use this command to install python-tcod in a user environment on MacOS. Ensure Python 3 is installed first. ```bash python3 -m pip install --user tcod ``` -------------------------------- ### Using Lucida custom font Source: https://github.com/libtcod/python-tcod/blob/main/fonts/libtcod/README.txt Example of loading a custom font named 'lucida' with 8x8 character size, greyscale format, and TCOD layout. ```bash ./samples_c -font fonts/lucida8x8_gs_tc.png -font-nb-char 32 8 -font-greyscale -font-tcod ``` -------------------------------- ### Using Caeldera custom font Source: https://github.com/libtcod/python-tcod/blob/main/fonts/libtcod/README.txt Example of loading a custom font named 'caeldera' with 8x8 character size, greyscale format, and TCOD layout. ```bash ./samples_c -font fonts/caeldera8x8_gs_tc.png -font-nb-char 32 8 -font-greyscale -font-tcod ``` -------------------------------- ### Verify tcod Import Source: https://github.com/libtcod/python-tcod/blob/main/docs/installation.md After installation, open the Python interpreter and attempt to import `tcod.context`. A successful import without an ImportError indicates a correct installation. ```python >python >>> import tcod.context ``` -------------------------------- ### Initialize tcod, load tileset, and open window Source: https://github.com/libtcod/python-tcod/blob/main/docs/tutorial/part-01.md Loads a specified tileset, fills in procedural block elements, and opens a tcod window. The window remains open within the 'with' block. Ensure 'tcod' is installed and the tileset path is correct. ```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() ``` -------------------------------- ### Using Celtic Garamond custom font Source: https://github.com/libtcod/python-tcod/blob/main/fonts/libtcod/README.txt Example of loading a custom font named 'celtic_garamond' with 10x10 character size, greyscale format, and TCOD layout. ```bash ./samples_c -font fonts/celtic_garamond_10x10_gs_tc.png -font-nb-char 32 8 -font-greyscale -font-tcod ``` -------------------------------- ### Install Dependencies on Debian-based Linux Source: https://github.com/libtcod/python-tcod/blob/main/CONTRIBUTING.md Install the required dependencies for tcod on Debian-based Linux distributions. This includes the C compiler, Python development headers, SDL2, and FFI. ```sh sudo apt install gcc python-dev libsdl2-dev libffi-dev ``` -------------------------------- ### Install Editable python-tcod on Windows Source: https://github.com/libtcod/python-tcod/blob/main/CONTRIBUTING.md Install an editable version of python-tcod on Windows after setting up the environment and downloading submodules. Use the 'py' command for Python execution. ```sh py -m pip install --editable . --verbose ``` -------------------------------- ### Using terminal8x8 greyscale font with row layout Source: https://github.com/libtcod/python-tcod/blob/main/fonts/libtcod/README.txt Example of how to load and use the terminal8x8 greyscale font with a row-based layout. Combine `-font-greyscale` and `-font-in-row` flags. ```bash ./samples_c -font fonts/terminal8x8_gs_ro.png -font-nb-char 16 16 -font-greyscale -font-in-row ``` -------------------------------- ### Update main.py with Global Variables and Game Loop Source: https://github.com/libtcod/python-tcod/blob/main/docs/tutorial/part-03.md This snippet shows the updated main function in main.py. It includes necessary imports, initializes the console and states, and starts the main game loop. ```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() ``` -------------------------------- ### Using terminal8x8 greyscale font with ASCII layout Source: https://github.com/libtcod/python-tcod/blob/main/fonts/libtcod/README.txt Example of how to load and use the terminal8x8 greyscale font with a standard ASCII layout. Use the `-font-greyscale` flag for greyscale fonts. ```bash ./samples_c -font fonts/terminal8x8_gs_as.png -font-nb-char 16 16 -font-greyscale ``` -------------------------------- ### Using Dundalk custom font Source: https://github.com/libtcod/python-tcod/blob/main/fonts/libtcod/README.txt Example of loading a custom font named 'dundalk' with 12x12 character size, greyscale format, and TCOD layout. ```bash ./samples_c -font fonts/dundalk12x12_gs_tc.png -font-nb-char 32 8 -font-greyscale -font-tcod ``` -------------------------------- ### Using terminal8x8 greyscale font with TCOD layout Source: https://github.com/libtcod/python-tcod/blob/main/fonts/libtcod/README.txt Example of how to load and use the terminal8x8 greyscale font with the TCOD specific layout. Combine `-font-greyscale` and `-font-tcod` flags. ```bash ./samples_c -font fonts/terminal8x8_gs_tc.png -font-nb-char 32 8 -font-greyscale -font-tcod ``` -------------------------------- ### Using terminal8x8 antialiased font with ASCII layout Source: https://github.com/libtcod/python-tcod/blob/main/fonts/libtcod/README.txt Example of how to load and use the terminal8x8 antialiased font with a standard ASCII layout using the C samples utility. Specify the font file and the number of characters per row and column. ```bash ./samples_c -font fonts/terminal8x8_aa_as.png -font-nb-char 16 16 ``` -------------------------------- ### Define Main Menu State Source: https://github.com/libtcod/python-tcod/blob/main/docs/tutorial/part-03.md Implements the main menu for the game, allowing options like starting a new game, continuing, or quitting. It inherits from `game.menus.ListMenu` and dynamically adds a 'Continue' option if a game world exists. ```python class MainMenu(game.menus.ListMenu): """Main/escape menu.""" __slots__ = () def __init__(self) -> None: """Initialize the main menu.""" items = [ game.menus.SelectItem("New game", self.new_game), game.menus.SelectItem("Quit", self.quit), ] if hasattr(g, "world"): items.insert(0, game.menus.SelectItem("Continue", self.continue_)) super().__init__( items=tuple(items), selected=0, x=5, y=5, ) @staticmethod def continue_() -> StateResult: """Return to the game.""" return Reset(InGame()) @staticmethod def new_game() -> StateResult: """Begin a new game.""" g.world = game.world_tools.new_world() return Reset(InGame()) @staticmethod def quit() -> StateResult: """Close the program.""" raise SystemExit ``` -------------------------------- ### Using terminal10x10 greyscale TCOD font Source: https://github.com/libtcod/python-tcod/blob/main/fonts/libtcod/README.txt Example of loading a terminal font with a 10x10 character size, greyscale format, and TCOD layout. This can serve as a template for creating new fonts. ```bash ./samples_c -font fonts/terminal10x10_gs_tc.png -font-nb-char 32 8 -font-greyscale -font-tcod ``` -------------------------------- ### Using terminal7x7 greyscale TCOD font Source: https://github.com/libtcod/python-tcod/blob/main/fonts/libtcod/README.txt Example of loading a terminal font with a 7x7 character size, greyscale format, and TCOD layout. This can serve as a template for creating new fonts. ```bash ./samples_c -font fonts/terminal7x7_gs_tc.png -font-nb-char 32 8 -font-greyscale -font-tcod ``` -------------------------------- ### Initialize and run the game loop Source: https://github.com/libtcod/python-tcod/blob/main/docs/tutorial/part-01.md Sets up the game window, creates an ExampleState instance centered on the console, and enters a loop to clear, draw, present, and process events. ```python ... def main() -> None: """Run ExampleState.""" 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) state = ExampleState(player_x=console.width // 2, player_y=console.height // 2) with tcod.context.new(console=console, tileset=tileset) as context: while True: console.clear() # Clear the console before any drawing state.on_draw(console) # Draw the current state context.present(console) # Display the console on the window for event in tcod.event.wait(): print(event) if isinstance(event, tcod.event.Quit): raise SystemExit if __name__ == "__main__": main() ... ``` -------------------------------- ### Basic Event Loop with Console Display Source: https://github.com/libtcod/python-tcod/blob/main/docs/tutorial/part-01.md This snippet initializes a console, displays 'Hello World', and enters a main loop to present the console and handle events. It demonstrates how to set up the context, render the console, and gracefully exit when the user attempts to close the window. ```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() ``` -------------------------------- ### Define an ExampleState class Source: https://github.com/libtcod/python-tcod/blob/main/docs/tutorial/part-01.md This class holds player coordinates and an on_draw method to render the player. It requires the 'attrs' and 'tcod' libraries. ```python from __future__ import annotations import attrs import tcod.console import tcod.context import tcod.event import tcod.tileset @attrs.define() class ExampleState: """Example state with a hard-coded player position.""" player_x: int """Player X position, left-most position is zero.""" player_y: int """Player Y position, top-most position is zero.""" def on_draw(self, console: tcod.console.Console) -> None: """Draw the player glyph.""" console.print(self.player_x, self.player_y, "@") ... ``` -------------------------------- ### Install Editable python-tcod on MacOS Source: https://github.com/libtcod/python-tcod/blob/main/CONTRIBUTING.md Install an editable version of python-tcod on MacOS after setting up the environment and downloading submodules. ```sh pip install --editable . --verbose ``` -------------------------------- ### Install python-tcod in PyCharm Virtual Environment Source: https://github.com/libtcod/python-tcod/blob/main/docs/installation.md Installs the tcod library within a PyCharm project's virtual environment using the integrated terminal. ```bash pip install tcod ``` -------------------------------- ### Create ECS Registry and Entities Source: https://github.com/libtcod/python-tcod/blob/main/docs/tutorial/part-02.md This snippet demonstrates how to initialize an ECS registry, create a player entity with components and tags, and scatter gold entities with random positions and values. ```python from __future__ import annotations from random import Random from tcod.ecs import Registry from game.components import Gold, Graphic, Position from game.tags import IsActor, IsItem, IsPlayer def new_world() -> Registry: """Return a freshly generated world.""" world = Registry() rng = world[None].components[Random] = Random() player = world[object()] player.components[Position] = Position(5, 5) player.components[Graphic] = Graphic(ord("@")) player.components[Gold] = 0 player.tags |= {IsPlayer, IsActor} for _ in range(10): gold = world[object()] gold.components[Position] = Position(rng.randint(0, 20), rng.randint(0, 20)) gold.components[Graphic] = Graphic(ord("$"), fg=(255, 255, 0)) gold.components[Gold] = rng.randint(1, 10) gold.tags |= {IsItem} return world ``` -------------------------------- ### Install python-tcod 6.0.7 for Python 2.7 Source: https://github.com/libtcod/python-tcod/blob/main/docs/installation.md Use this command to install a specific version of python-tcod for Python 2.7 environments. Ensure you are using the python2 interpreter. ```bash python2 -m pip install tcod==6.0.7 ``` -------------------------------- ### Build Directory Distribution with PyInstaller Source: https://github.com/libtcod/python-tcod/blob/main/examples/distribution/PyInstaller/README.rst Use PyInstaller with the main.spec file to create a directory distribution of the application. ```bash PyInstaller main.spec ``` -------------------------------- ### Game Namespace Package Source: https://github.com/libtcod/python-tcod/blob/main/docs/tutorial/part-02.md Initialize a namespace package for organizing game modules. ```python """Game namespace package.""" ``` -------------------------------- ### Upgrade python-tcod to Latest Version Source: https://github.com/libtcod/python-tcod/blob/main/docs/installation.md Use this command to upgrade your python-tcod installation to the most recent release. Ensure you are using Python 3. ```bash python3 -m pip install --upgrade tcod ``` -------------------------------- ### Build Single-File Distribution with PyInstaller Source: https://github.com/libtcod/python-tcod/blob/main/examples/distribution/PyInstaller/README.rst Use PyInstaller with the main.spec file and the --onefile option to create a single executable file. Note that single-file distributions may have performance downsides. ```bash PyInstaller main.spec --onefile ``` -------------------------------- ### Add tcod requirement to requirements.txt Source: https://github.com/libtcod/python-tcod/blob/main/docs/faq.md Specify the tcod library in a requirements.txt file for PyCharm to automatically install it into the project's virtual environment. ```python # requirements.txt # https://pip.pypa.io/en/stable/cli/pip_install/#requirements-file-format tcod ``` -------------------------------- ### Get Previous State in Stack Source: https://github.com/libtcod/python-tcod/blob/main/docs/tutorial/part-03.md Retrieves the state immediately preceding the given state in the stack. Returns None if the given state is the first one. ```python def get_previous_state(state: State) -> State | None: """Return the state before `state` in the stack if it exists.""" current_index = next(index for index, value in enumerate(g.states) if value is state) return g.states[current_index - 1] if current_index > 0 else None ``` -------------------------------- ### Basic Game Loop with Event Handling Source: https://github.com/libtcod/python-tcod/blob/main/docs/tutorial/part-01.md This snippet demonstrates a fundamental game loop. It initializes the console and tileset, enters a loop to clear the screen, draw the game state, present the console, and process events. Player movement and exiting the application are handled within the event loop. ```python from __future__ import annotations import attrs import tcod.console import tcod.context import tcod.event import tcod.tileset @attrs.define() class ExampleState: """Example state with a hard-coded player position.""" player_x: int """Player X position, left-most position is zero.""" player_y: int """Player Y position, top-most position is zero.""" def on_draw(self, console: tcod.console.Console) -> None: """Draw the player glyph.""" console.print(self.player_x, self.player_y, "@") def on_event(self, event: tcod.event.Event) -> None: """Move the player on events and handle exiting. Movement is hard-coded.""" match event: case tcod.event.Quit(): raise SystemExit case tcod.event.KeyDown(sym=tcod.event.KeySym.LEFT): self.player_x -= 1 case tcod.event.KeyDown(sym=tcod.event.KeySym.RIGHT): self.player_x += 1 case tcod.event.KeyDown(sym=tcod.event.KeySym.UP): self.player_y -= 1 case tcod.event.KeyDown(sym=tcod.event.KeySym.DOWN): self.player_y += 1 def main() -> None: """Run ExampleState.""" 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) state = ExampleState(player_x=console.width // 2, player_y=console.height // 2) with tcod.context.new(console=console, tileset=tileset) as context: while True: console.clear() state.on_draw(console) context.present(console) for event in tcod.event.wait(): print(event) state.on_event(event) # Pass events to the state if __name__ == "__main__": main() ``` -------------------------------- ### Forcing Renderer and VSync Options Source: https://github.com/libtcod/python-tcod/blob/main/CHANGELOG.md Set environment variables to force specific renderer and vsync options. This is useful for controlling how the game is rendered. ```bash TCOD_RENDERER=sdl2 TCOD_VSYNC=1 ``` -------------------------------- ### Using legacy terminal font Source: https://github.com/libtcod/python-tcod/blob/main/fonts/libtcod/README.txt Example of how to use the older, non-antialiased terminal font provided with libtcod 1.3.2. This font still works with the samples utility. ```bash ./samples_c -font terminal.png -font-nb-char 16 16 ``` -------------------------------- ### Main Game Script Source: https://github.com/libtcod/python-tcod/blob/main/docs/tutorial/part-02.md This is the updated main script for the python-tcod tutorial. It includes necessary imports, initializes the game context, world, and game state, and contains the main game loop for drawing and event handling. ```python #!/usr/bin/env python3 """Main entry-point module. This script is used to start the program.""" from __future__ import annotations import tcod.console import tcod.context import tcod.event import tcod.tileset import g import game.states import game.world_tools 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) console = tcod.console.Console(80, 50) state = game.states.InGame() g.world = game.world_tools.new_world() with tcod.context.new(console=console, tileset=tileset) as g.context: while True: # Main loop console.clear() # Clear the console before any drawing state.on_draw(console) # Draw the current state g.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) state.on_event(event) # Dispatch events to the state if __name__ == "__main__": main() ``` -------------------------------- ### Selectable Menu Item Implementation Source: https://github.com/libtcod/python-tcod/blob/main/docs/tutorial/part-03.md A concrete implementation of MenuItem that represents a clickable menu option. It handles keyboard (Enter) and mouse clicks to trigger its associated callback. ```python """Clickable menu item.""" label: str callback: Callable[[], StateResult] def on_event(self, event: tcod.event.Event) -> StateResult: """Handle events selecting this item.""" match event: case tcod.event.KeyDown(sym=sym) if sym in {KeySym.RETURN, KeySym.RETURN2, KeySym.KP_ENTER}: return self.callback() case tcod.event.MouseButtonUp(button=tcod.event.MouseButton.LEFT): return self.callback() case _: return None def on_draw(self, console: tcod.console.Console, x: int, y: int, highlight: bool) -> None: """Render this items label.""" console.print(x, y, self.label, fg=(255, 255, 255), bg=(64, 64, 64) if highlight else (0, 0, 0)) ``` -------------------------------- ### Using terminal8x8 antialiased font with row layout Source: https://github.com/libtcod/python-tcod/blob/main/fonts/libtcod/README.txt Example of how to load and use the terminal8x8 antialiased font with a row-based layout. Use the `-font-in-row` flag to indicate this layout. ```bash ./samples_c -font fonts/terminal8x8_aa_ro.png -font-nb-char 16 16 -font-in-row ```