|
| 1 | +"""Hello world using tcod's SDL API and using Pillow for the TTF rendering.""" |
| 2 | +from pathlib import Path |
| 3 | + |
| 4 | +import numpy as np |
| 5 | +import tcod |
| 6 | +import tcod.sdl.render |
| 7 | +import tcod.sdl.video |
| 8 | +from PIL import Image, ImageDraw, ImageFont # type: ignore # pip install Pillow |
| 9 | + |
| 10 | +CURRENT_DIR = Path(__file__).parent # Directory of this script. |
| 11 | +font = ImageFont.truetype(bytes(CURRENT_DIR / "DejaVuSerif.ttf"), size=18) # Preloaded font file. |
| 12 | + |
| 13 | + |
| 14 | +def render_text(renderer: tcod.sdl.render.Renderer, text: str) -> tcod.sdl.render.Texture: |
| 15 | + """Render text, upload it to VRAM, then return it as an SDL Texture.""" |
| 16 | + # Use Pillow normally to render the font. This code is standard. |
| 17 | + width, height = font.getsize(text) |
| 18 | + image = Image.new("RGBA", (width, height)) |
| 19 | + draw = ImageDraw.Draw(image) |
| 20 | + draw.text((0, 0), text, font=font) |
| 21 | + # Push to VRAM using SDL. |
| 22 | + texture = renderer.upload_texture(np.asarray(image)) |
| 23 | + texture.blend_mode = tcod.sdl.render.BlendMode.BLEND # Enable alpha blending by default. |
| 24 | + return texture |
| 25 | + |
| 26 | + |
| 27 | +def main() -> None: |
| 28 | + """Show hello world until the window is closed.""" |
| 29 | + # Open an SDL window and renderer. |
| 30 | + window = tcod.sdl.video.new_window(720, 480, flags=tcod.sdl.video.WindowFlags.RESIZABLE) |
| 31 | + renderer = tcod.sdl.render.new_renderer(window, target_textures=True) |
| 32 | + # Render the text once, then reuse the texture. |
| 33 | + hello_world = render_text(renderer, "Hello World") |
| 34 | + hello_world.color_mod = (64, 255, 64) # Set the color when copied. |
| 35 | + |
| 36 | + while True: |
| 37 | + renderer.draw_color = (0, 0, 0, 255) |
| 38 | + renderer.clear() |
| 39 | + renderer.copy(hello_world, dest=(0, 0, hello_world.width, hello_world.height)) |
| 40 | + renderer.present() |
| 41 | + for event in tcod.event.get(): |
| 42 | + if isinstance(event, tcod.event.Quit): |
| 43 | + raise SystemExit() |
| 44 | + |
| 45 | + |
| 46 | +if __name__ == "__main__": |
| 47 | + main() |
0 commit comments