gpt4 book ai didi

python - 在pygame中循环

转载 作者:太空宇宙 更新时间:2023-11-03 15:46:42 25 4
gpt4 key购买 nike

我正在尝试将 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 语句中使用它?

最佳答案

仔细观察这个 block :

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

到 block ,它应该工作。

顺便说一句,您可以在 if 语句中使用此循环的 i(按钮 ID)。

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

这就是 block 可能看起来的样子:

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中循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49544142/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com