While loop in pygame


November 2018


132 time


I'm trying to add PS4 input to my python code, so I wanted to make it whenever I'm holding down a button, it prints as long as it held down for, not just the one time. I tried many different variations of while loops but it just spams my console with text so I know im doing something wrong. Any help would be appreciated.

import pygame

BLACK    = (   0,   0,   0)
WHITE    = ( 255, 255, 255)

class TextPrint:
    def __init__(self):
        self.font = pygame.font.Font(None, 25)

    def print(self, screen, textString):
        textBitmap = self.font.render(textString, True, BLACK)
        screen.blit(textBitmap, [self.x, self.y])
        self.y += self.line_height

    def reset(self):
        self.x = 30
        self.y = 30
        self.line_height = 20

    def indent(self):
        self.x += 10

    def unindent(self):
        self.x -= 10


size = [800, 500]
screen = pygame.display.set_mode(size)

pygame.display.set_caption("My Game")

done = False

clock = pygame.time.Clock()


textPrint = TextPrint()

while done==False:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:

        if event.type == pygame.JOYBUTTONDOWN:
            print("Joystick button pressed.")
        if event.type == pygame.JOYBUTTONUP:
            print("Joystick button released.")


    joystick_count = pygame.joystick.get_count()

    for i in range(joystick_count):
        joystick = pygame.joystick.Joystick(i)

        name = joystick.get_name()
        textPrint.print(screen, "Joystick name: {}".format(name) )

        buttons = joystick.get_numbuttons()
        textPrint.print(screen, "Number of buttons: {}".format(buttons) )

        for i in range( buttons ):
            button = joystick.get_button( i )
            textPrint.print(screen, "Button {:>2} value: {}".format(i,button) )



pygame.quit ()     

Modified code from official pygame documentation
Also a side question, but its not priority: How would i know exactly which button is being pressed and use it in an if statement?

1 answers


Посмотрите внимательно на этот блок:

for i in range( buttons ):
    button = joystick.get_button( i )
    textPrint.print(screen, "Button {:>2} value: {}".format(i,button) )

textPrint.printотрисовывает текст с помощью кнопки ID ( i) и его заявление ( button) (0 отпущена, 1 нажата). Так что , если вам нужно напечатать текст , пока нажата кнопка, просто добавьте это:

if button == 1:
    print("Button "+str(i)+" is pressed")

к блоку, и он должен работать.

Кстати, вы можете использовать iкнопку (ID) этого цикла , чтобы использовать в качестве , если заявление.

if button == 1:
    if i == 2:
        print("A is pressed")
    elif i == 1:
        print("B is pressed")

Вот как блок может выглядеть после того, как все:

for i in range( buttons ):
    button = joystick.get_button( i )
    if button == 1: #if any button is pressed
        if i == 2:  #if A button is pressed
            print("A is pressed")
        if i == 1:  #if B button is pressed
            print("B is pressed")
    textPrint.print(screen, "Button {:>2} value: {}".format(i,button) )