python-pygame中的while循环
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python-pygame中的while循环,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2532字,纯文字阅读大概需要4分钟。
内容图文
![python-pygame中的while循环](/upload/InfoBanner/zyjiaocheng/669/43320f989d8b4e909a22cb245f4cd1c4.jpg)
我正在尝试将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)及其声明(按钮)(释放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循环全部内容,希望文章能够帮你解决python-pygame中的while循环所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。