import pygame pygame.init() screen = pygame.display.set_mode((640, 480)) clock = pygame.time.Clock() # Constants HAT_REPEAT_DELAY = 300 # milliseconds before first repeat HAT_REPEAT_INTERVAL = 100 # milliseconds between repeats # State hat_direction = (0, 0) hat_timer = 0 hat_first_press = True # Init joystick pygame.joystick.init() if pygame.joystick.get_count() > 0: joystick = pygame.joystick.Joystick(0) joystick.init() def handle_hat_repeat(): global hat_timer, hat_first_press now = pygame.time.get_ticks() if hat_direction != (0, 0): if hat_first_press: if now - hat_timer >= HAT_REPEAT_DELAY: hat_timer = now hat_first_press = False post_hat_repeat_event() else: if now - hat_timer >= HAT_REPEAT_INTERVAL: hat_timer = now post_hat_repeat_event() def post_hat_repeat_event(): pygame.event.post(pygame.event.Event(pygame.USEREVENT, { "type_name": "JOYHATREPEAT", "value": hat_direction })) running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False elif event.type == pygame.JOYHATMOTION: hat_direction = event.value hat_timer = pygame.time.get_ticks() hat_first_press = True elif event.type == pygame.USEREVENT and event.dict.get("type_name") == "JOYHATREPEAT": print(f"Repeated hat: {event.dict['value']}") handle_hat_repeat() screen.fill((0, 0, 0)) pygame.display.flip() clock.tick(60)