在pygame

时间:2018-03-28 21:03:45

标签: python pygame

我试图将PS4输入添加到我的python代码中,所以每当我按住一个按钮时我都会想要它,只要按住它就会打印,而不仅仅是一次。我尝试了许多不同的while循环变种,但它只是用文本来阻止我的控制台,所以我知道我做错了。任何帮助,将不胜感激。

import pygame


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


class TextPrint:
    def __init__(self):
        self.reset()
        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


pygame.init()


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

pygame.display.set_caption("My Game")

done = False

clock = pygame.time.Clock()

pygame.joystick.init()

textPrint = TextPrint()

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


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


    screen.fill(WHITE)
    textPrint.reset()

    joystick_count = pygame.joystick.get_count()

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

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

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

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

        pygame.display.flip()

clock.tick(20)

pygame.quit ()     


来自官方pygame documentation 的修改代码
也是一个附带问题,但不是优先事项: 我如何确切地知道哪个按钮被按下并在if语句中使用它?

1 个答案:

答案 0 :(得分:3)

仔细看看这个街区:

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语句中使用。

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) )