Pure Python wrapper around SDL2 libraries for cross-platform multimedia development
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
High-precision timing functions for animations, frame rate control, and custom timer callbacks. PySDL2 provides comprehensive timing capabilities for time-sensitive applications like games and multimedia software.
Functions for getting current time and implementing delays.
def SDL_GetTicks() -> int:
"""
Get the number of milliseconds since SDL library initialization.
Returns:
Milliseconds since SDL_Init() was called
"""
def SDL_GetTicks64() -> int:
"""
Get the number of milliseconds since SDL library initialization as 64-bit value.
Returns:
Milliseconds since SDL_Init() as 64-bit integer (SDL 2.0.18+)
"""
def SDL_Delay(ms: int) -> None:
"""
Wait a specified number of milliseconds before returning.
Parameters:
- ms: milliseconds to delay
"""High-resolution performance counter functions for precise timing measurements.
def SDL_GetPerformanceCounter() -> int:
"""
Get the current value of the high resolution counter.
Returns:
Current counter value in platform-specific units
"""
def SDL_GetPerformanceFrequency() -> int:
"""
Get the count per second of the high resolution counter.
Returns:
Counter frequency in counts per second
"""Timer callback system for creating custom periodic or one-shot timers.
def SDL_AddTimer(interval: int, callback: SDL_TimerCallback, param: Any) -> int:
"""
Add a new timer to the pool of timers already running.
Parameters:
- interval: timer interval in milliseconds
- callback: function to call when timer expires
- param: parameter to pass to callback function
Returns:
Timer ID on success, 0 on error
"""
def SDL_RemoveTimer(timer_id: int) -> bool:
"""
Remove a timer knowing its ID.
Parameters:
- timer_id: ID of timer to remove
Returns:
True if timer was removed successfully
"""def SDL_TICKS_PASSED(A: int, B: int) -> bool:
"""
Compare SDL tick values for proper overflow handling.
Parameters:
- A: first tick value
- B: second tick value
Returns:
True if A has passed B, accounting for overflow
"""import sdl2
# Initialize SDL
sdl2.SDL_Init(sdl2.SDL_INIT_TIMER)
# Get current time
start_time = sdl2.SDL_GetTicks()
# Do some work...
sdl2.SDL_Delay(1000) # Wait 1 second
# Calculate elapsed time
elapsed = sdl2.SDL_GetTicks() - start_time
print(f"Elapsed time: {elapsed}ms")import sdl2
# Get high-resolution timer frequency
frequency = sdl2.SDL_GetPerformanceFrequency()
print(f"Timer frequency: {frequency} Hz")
# Measure precise timing
start_counter = sdl2.SDL_GetPerformanceCounter()
# Do time-critical work...
end_counter = sdl2.SDL_GetPerformanceCounter()
# Calculate elapsed time in seconds
elapsed_seconds = (end_counter - start_counter) / frequency
elapsed_ms = elapsed_seconds * 1000
print(f"Precise elapsed time: {elapsed_ms:.3f}ms")import sdl2
# Target 60 FPS
TARGET_FPS = 60
FRAME_TIME = 1000 // TARGET_FPS # ~16.67ms per frame
# Game loop with frame rate control
running = True
last_time = sdl2.SDL_GetTicks()
while running:
current_time = sdl2.SDL_GetTicks()
frame_time = current_time - last_time
if frame_time >= FRAME_TIME:
# Update game logic
update_game()
# Render frame
render_frame()
last_time = current_time
else:
# Sleep for remaining frame time
sleep_time = FRAME_TIME - frame_time
if sleep_time > 0:
sdl2.SDL_Delay(sleep_time)import sdl2
from ctypes import c_void_p
def timer_callback(interval, param):
"""Timer callback function"""
print(f"Timer fired! Interval: {interval}ms")
return interval # Return interval to repeat, 0 to stop
# Initialize SDL
sdl2.SDL_Init(sdl2.SDL_INIT_TIMER)
# Add a timer that fires every 500ms
timer_id = sdl2.SDL_AddTimer(500, timer_callback, None)
if timer_id != 0:
print(f"Timer added with ID: {timer_id}")
# Let timer run for a while
sdl2.SDL_Delay(3000)
# Remove the timer
if sdl2.SDL_RemoveTimer(timer_id):
print("Timer removed successfully")
else:
print("Failed to add timer")import sdl2
class GameTimer:
def __init__(self):
self.last_time = sdl2.SDL_GetPerformanceCounter()
self.frequency = sdl2.SDL_GetPerformanceFrequency()
def get_delta_time(self):
"""Get delta time in seconds since last call"""
current_time = sdl2.SDL_GetPerformanceCounter()
delta = (current_time - self.last_time) / self.frequency
self.last_time = current_time
return delta
# Usage in game loop
timer = GameTimer()
while running:
dt = timer.get_delta_time()
# Update game objects with delta time
player.update(dt)
enemies.update(dt)
# Render frame
render()# Timer callback function type
SDL_TimerCallback = Callable[[int, Any], int]
"""
Timer callback function signature.
Parameters:
- interval: timer interval in milliseconds
- param: user data passed to SDL_AddTimer
Returns:
- Next timer interval in milliseconds, or 0 to cancel timer
"""
SDL_TimerID = int
"""Timer identifier returned by SDL_AddTimer."""Install with Tessl CLI
npx tessl i tessl/pypi-pysdl2