我正在尝试将 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 语句中使用它?
最佳答案
仔细看看这个块:
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) )
关于python - pygame中的while循环,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49544142/