11import pygame
22import logging
3-
4- # Configure logging for debugging
5- logging .basicConfig (level = logging .DEBUG )
3+ import time
64
75class Gamepad :
8- def __init__ (self ):
6+ def __init__ (self , retry_interval = 1 , max_retries = 5 ):
97 pygame .init ()
108 pygame .joystick .init ()
11- self .joystick = pygame .joystick .Joystick (0 )
12- self .joystick .init ()
9+ self .joystick = None
10+ self .retry_interval = retry_interval
11+ self .max_retries = max_retries
12+ self ._initialize_gamepad ()
13+
14+ def _initialize_gamepad (self ):
15+ """Initialize gamepad with retry logic"""
16+ for attempt in range (self .max_retries ):
17+ try :
18+ if pygame .joystick .get_count () > 0 :
19+ self .joystick = pygame .joystick .Joystick (0 )
20+ self .joystick .init ()
21+ logging .info (f"Gamepad connected: { self .joystick .get_name ()} " )
22+ return
23+ else :
24+ logging .warning (f"No gamepad detected (attempt { attempt + 1 } /{ self .max_retries } )" )
25+ except Exception as e :
26+ logging .error (f"Initialization error: { str (e )} " )
27+
28+ time .sleep (self .retry_interval )
29+
30+ raise RuntimeError ("Failed to initialize gamepad after multiple attempts" )
1331
1432 def get_input (self ):
15- """
16- Get input from the gamepad.
17- """
33+ """Get normalized input from gamepad with deadzone handling"""
34+ if not self .joystick :
35+ raise RuntimeError ("Gamepad not initialized" )
36+
1837 try :
1938 pygame .event .pump ()
20- x_axis = self .joystick .get_axis (0 ) # Left stick X-axis
21- y_axis = self .joystick .get_axis (1 ) # Left stick Y-axis
22- logging .debug (f"Gamepad input: x_axis={ x_axis } , y_axis={ y_axis } " )
39+
40+ # Add deadzone threshold (adjust as needed)
41+ deadzone = 0.1
42+
43+ # Get axis values with deadzone filtering
44+ x_axis = self ._apply_deadzone (self .joystick .get_axis (0 ), deadzone )
45+ y_axis = self ._apply_deadzone (self .joystick .get_axis (1 ), deadzone )
46+
47+ logging .debug (f"Gamepad input - X: { x_axis :.2f} , Y: { y_axis :.2f} " )
2348 return x_axis , y_axis
49+
2450 except Exception as e :
25- logging .error (f"An error occurred while reading gamepad input: { e } " )
26- raise
51+ logging .error (f"Input error: { str (e )} " )
52+ raise
53+
54+ def _apply_deadzone (self , value , threshold ):
55+ """Apply deadzone to axis values"""
56+ if abs (value ) < threshold :
57+ return 0.0
58+ return value
59+
60+ def __del__ (self ):
61+ if self .joystick :
62+ self .joystick .quit ()
63+ pygame .quit ()
0 commit comments