-3

This code goes into infinite loop. I cant use A button on xbox 360 controller

import pygame
from pygame import joystick


pygame.init()


joystick = pygame.joystick.Joystick(0)


pygame.joystick.init()

print("start")
while True:

    if joystick.get_button(0) == 1  :
        print("stoped")
        break
Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92

2 Answers2

1

I cant use A button on xbox 360 controller

Personnaly, I can, so this seems to be possible. You are just missing that pretty much every user input needs to be updated by pygame through pygame.event.get().

From the pygame documentation:

Once the device is initialized the pygame event queue will start receiving events about its input.

So, apparently you need to get the events in the while loop like such to make the joystick work:

import pygame
from pygame.locals import *

pygame.init()

joystick = pygame.joystick.Joystick(0)

while True:
    for event in pygame.event.get(): # get the events (update the joystick)
        if event.type == QUIT: # allow to click on the X button to close the window
            pygame.quit()
            exit()

    if joystick.get_button(0):
        print("stopped")
        break

Also,

  1. In the line if joystick.get_button(0) == 1, you don't need to type == 1 because the statement is already True.
  2. You are initializing pygame.joystick twice: through the line pygame.init() and pygame.joystick.init().
  3. You don't need to type from pygame import joystick because you already already have it in the line import pygame.
D_00
  • 1,440
  • 2
  • 13
  • 32
0

You can take this as reference and use it in your own way.

import pygame
import sys

pygame.init()
pygame.joystick.init()
clock = pygame.time.Clock()

WIDTH,HEIGHT = 500,500
WHITE = (255,255,255)
BLUE = (0,0,255)
BLUISH = (75,75,255)
YELLOW =(255,255,0)
screen = pygame.display.set_mode((WIDTH,HEIGHT))

smile = pygame.image.load("smile.jpg")
smile = pygame.transform.scale(smile,(WIDTH,HEIGHT))

idle = pygame.image.load("idle.jpg")
idle = pygame.transform.scale(idle,(WIDTH,HEIGHT))

joysticks = [pygame.joystick.Joystick(x) for x in range(pygame.joystick.get_count())]
    
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()

        elif  event.type == pygame.JOYBUTTONDOWN:
            if  event.button == 0: #press A button to smile
                screen.fill(WHITE)
                screen.blit(smile,(0,0))
                pygame.display.update()
                clock.tick(10)
        elif  event.type == pygame.JOYBUTTONUP:
            if  event.button == 0:
                screen.fill(WHITE)
                screen.blit(idle,(0,0))
                pygame.display.update()
                clock.tick(10)

Button Reference

Ansh
  • 58
  • 6