Python Forum
Cannot get pygame.JOYBUTTONDOWN to register - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Game Development (https://python-forum.io/forum-11.html)
+--- Thread: Cannot get pygame.JOYBUTTONDOWN to register (/thread-36380.html)



Cannot get pygame.JOYBUTTONDOWN to register - dboxall123 - Feb-13-2022

Hello all,

I'm messing around with a usb joystick I got online, and I cannot seem to get pygame to register it. I have written the following, simple code:

import pygame as pg

pg.init()
pg.joystick.init()

screen = pg.display.set_mode((500,500))

running = True

while running:
	for event in pg.event.get():
		if event.type == pg.QUIT:
			running = False
		if event.type == pg.JOYBUTTONDOWN:
			print("button down")
		if event.type == pg.JOYBUTTONUP:
			print("button up")
			
	screen.fill((255,255,255))
	pg.display.update()
			
pg.quit()
I expected it to print when i hit a button, but it doesn't seem to be registering at all, and I don't understand why. I also copied the example code from the pygame page, and that worked. What am I missing?


RE: Cannot get pygame.JOYBUTTONDOWN to register - BashBedlam - Feb-14-2022

Try initializing the joystick individually. Assuming that it's in the zero position, this should work.
joystick_0 = pg.joystick.Joystick (0)
joystick_0 .init()
This works on my system when only one joystick is plugged in.
import pygame as pg
 
pg.init()
joystick_0 = pg.joystick.Joystick (0)
joystick_0 .init()
 
screen = pg.display.set_mode((500,500))
 
running = True
 
while running:
	for event in pg.event.get():
		if event.type == pg.QUIT:
			running = False
		if event.type == pg.JOYBUTTONDOWN:
			print("button down")
		if event.type == pg.JOYBUTTONUP:
			print("button up")
			 
	screen.fill((255,255,255))
	pg.display.update()
             
pg.quit()
Output:
pygame 2.0.1 (SDL 2.0.14, Python 3.8.10) Hello from the pygame community. https://www.pygame.org/contribute.html button down button up button down button up



RE: Cannot get pygame.JOYBUTTONDOWN to register - dboxall123 - Feb-14-2022

That works, thank you! I thought I was doing the same thing as the example in the pygame docs, but upon closer inspection, I found the following lines inside the main loop:

    # For each joystick:
    for i in range(joystick_count):
        joystick = pygame.joystick.Joystick(i)
        joystick.init()
It makes sense why mine wasn't working now, many thanks.


RE: Cannot get pygame.JOYBUTTONDOWN to register - BashBedlam - Feb-14-2022

Always happy to help Smile


RE: Cannot get pygame.JOYBUTTONDOWN to register - earlenoyes - May-19-2022

Thanks for trying to help!