Skip to content

Commit db8c3a9

Browse files
sdl2_demo: capture keypresses on screen
1 parent 7a7d3a1 commit db8c3a9

1 file changed

Lines changed: 53 additions & 1 deletion

File tree

draft_code/sdl2_demo.py

Lines changed: 53 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,38 @@
11
import sdl2
22
import sdl2.ext
3+
import sdl2.sdlttf
4+
import ctypes
35

6+
# Initialize SDL2 and TTF
47
sdl2.ext.init()
8+
sdl2.sdlttf.TTF_Init()
9+
10+
# Create window and renderer
511
window = sdl2.ext.Window("Test", size=(800, 600))
612
window.show()
13+
renderer = sdl2.ext.Renderer(window)
14+
15+
# Load font
16+
font = sdl2.sdlttf.TTF_OpenFont(b"/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", 24)
17+
if not font:
18+
print("Failed to load font!")
19+
exit(1)
20+
21+
# Initialize text variables
22+
last_key = "No key pressed"
23+
text_surface = None
24+
text_texture = None
25+
26+
def render_text(text):
27+
global text_surface, text_texture
28+
# Clean up previous texture
29+
if text_texture:
30+
sdl2.SDL_DestroyTexture(text_texture)
31+
32+
# Create new surface and texture
33+
color = sdl2.SDL_Color(r=255, g=255, b=255)
34+
text_surface = sdl2.sdlttf.TTF_RenderText_Solid(font, text.encode('utf-8'), color)
35+
text_texture = sdl2.SDL_CreateTextureFromSurface(renderer.sdlrenderer, text_surface)
736

837
running = True
938
while running:
@@ -12,5 +41,28 @@
1241
if event.type == sdl2.SDL_QUIT:
1342
running = False
1443
elif event.type == sdl2.SDL_KEYDOWN:
15-
print(f"Key pressed: {event.key.keysym.sym}")
44+
# Update text with pressed key
45+
last_key = f"Key pressed: {sdl2.SDL_GetKeyName(event.key.keysym.sym).decode()}"
46+
render_text(last_key)
47+
48+
# Clear screen
49+
renderer.clear()
50+
51+
# Render text if available
52+
if text_texture:
53+
w, h = ctypes.c_int(), ctypes.c_int()
54+
sdl2.SDL_QueryTexture(text_texture, None, None, ctypes.byref(w), ctypes.byref(h))
55+
dstrect = sdl2.SDL_Rect(x=10, y=10, w=w.value, h=h.value)
56+
sdl2.SDL_RenderCopy(renderer.sdlrenderer, text_texture, None, dstrect)
57+
58+
# Update display
59+
renderer.present()
60+
61+
# Cleanup
62+
if text_texture:
63+
sdl2.SDL_DestroyTexture(text_texture)
64+
if text_surface:
65+
sdl2.SDL_FreeSurface(text_surface)
66+
sdl2.sdlttf.TTF_CloseFont(font)
67+
sdl2.sdlttf.TTF_Quit()
1668
sdl2.ext.quit()

0 commit comments

Comments
 (0)