"""Gamepad input: hot-plugging, axes with a dead zone, buttons and the D-pad (hat).""" import pygame DEADZONE = 0.2 pygame.init() screen = pygame.display.set_mode((640, 360)) clock = pygame.time.Clock() font = pygame.font.Font(None, 26) joysticks = {} # instance_id -> Joystick pos = pygame.Vector2(320, 180) running = True while running: dt = clock.tick(60) / 1000 for event in pygame.event.get(): if event.type == pygame.QUIT: running = False elif event.type == pygame.JOYDEVICEADDED: # also sent for pads connected at start-up joy = pygame.joystick.Joystick(event.device_index) joysticks[joy.get_instance_id()] = joy print("Connected:", joy.get_name()) elif event.type == pygame.JOYDEVICEREMOVED: joysticks.pop(event.instance_id, None) print("Disconnected") elif event.type == pygame.JOYBUTTONDOWN: print("Button", event.button, "on pad", event.instance_id) move = pygame.Vector2() for joy in joysticks.values(): x, y = joy.get_axis(0), joy.get_axis(1) # left stick on most pads if abs(x) > DEADZONE: move.x += x if abs(y) > DEADZONE: move.y += y if joy.get_numhats(): hx, hy = joy.get_hat(0) # D-pad: y is +1 for up move += (hx, -hy) keys = pygame.key.get_pressed() # keyboard fallback move += (keys[pygame.K_RIGHT] - keys[pygame.K_LEFT], keys[pygame.K_DOWN] - keys[pygame.K_UP]) if move.length_squared() > 1: move.scale_to_length(1) pos += move * 260 * dt pos.x = max(20, min(620, pos.x)) pos.y = max(20, min(340, pos.y)) screen.fill((20, 26, 46)) pygame.draw.circle(screen, (244, 197, 49), pos, 18) status = ", ".join(j.get_name() for j in joysticks.values()) or "No gamepad connected (arrow keys work too)" screen.blit(font.render(status, True, (230, 236, 247)), (16, 16)) pygame.display.flip() pygame.quit()