我正在学习Pygame制作带有Python的游戏。但是,我遇到了一个问题。我正在尝试检测播放器当前何时单击屏幕,但是我的代码无法正常工作。我的代码实际上是搞砸了,还是我正在使用的在线Pygame编译器?
import pygame
pygame.init()
screen = pygame.display.set_mode((800, 800))
while True:
pygame.display.update()
mouse = pygame.mouse.get_pressed()
if mouse:
print("You are clicking")
else:
print("You released")
当我运行此代码时,输出控制台在每秒几千次内向文本“您正在单击”发送垃圾邮件。即使我没有单击屏幕,它仍然会显示此信息。即使我的鼠标是不是在屏幕上。相同的文字。一遍又一遍。Pygame是否正确执行我的程序?
要学习Pygame,我使用的是开发人员提供的官方文档。https://www.pygame.org/docs/这是一种过时的学习方法,这就是为什么我的代码继续运行错误的原因吗?
pygame.mouse.get_pressed()
处理事件时将评估返回的坐标。您需要通过pygame.event.pump()
或处理事件pygame.event.get()
。
对于游戏的每一帧,您都需要对事件队列进行某种调用。这样可以确保您的程序可以与操作系统的其余部分进行内部交互。
pygame.mouse.get_pressed()
返回表示所有鼠标按钮状态的布尔值序列。您必须评估是否any
按了按钮(any(buttons)
)或订阅是否按了特殊按钮(例如buttons[0]
)。
例如:
import pygame
pygame.init()
screen = pygame.display.set_mode((800, 800))
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
buttons = pygame.mouse.get_pressed()
# if buttons[0]: # for the left mouse button
if any(buttons): # for any mouse button
print("You are clicking")
else:
print("You released")
pygame.display.update()
如果只想检测分别释放鼠标键的时间,则必须实现MOUSEBUTTONDOWN
and MOUSEBUTTONUP
(请参阅pygame.event
模块):
import pygame
pygame.init()
screen = pygame.display.set_mode((800, 800))
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.MOUSEBUTTONDOWN:
print("You are clicking", event.button)
if event.type == pygame.MOUSEBUTTONUP:
print("You released", event.button)
pygame.display.update()
当pygame.mouse.get_pressed()
返回按钮的当前状态时,MOUSEBUTTONDOWN
和MOUSEBUTTONUP
仅在按下按钮时出现。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句