0
每当我点击广场一次,它会打印文本“你打开了一个箱子!”无数次,但我希望程序仅在每次点击时打印一次,即使我按住鼠标按钮。我该如何调整或添加?我想停止这个'if statement'重复
import pygame
pygame.init()
pygame.display.set_caption('Crash!')
window = pygame.display.set_mode((300, 300))
running = True
#Draw Once
Rectplace = pygame.draw.rect(window, (255, 0, 0),(100, 100, 100, 100))
pygame.display.update()
#Main Loop
while running:
#mouse position and button clicking
pos = pygame.mouse.get_pos()
(pressed1,pressed2,pressed3) = pygame.mouse.get_pressed()
#if statement
if Rectplace.collidepoint(pos) and pressed1 == 1:
print("You have opened a chest!")
#Quit pygame
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.quit()
请同时给我调整好的代码;这将不胜感激。提前致谢!
我不知道pygame的,但通常有除了'pressed'事件'released'事件。试着检查一下。 – domsson
我会建议某种闩锁。假设你有一系列箱子,每个箱子都有其坐标和内容以及是否打开。 因此,如果Rectplace.collidepoint(pos)和pressed 1 == 1和chest.opened == False: – Gauthier
我只注意到您在循环中使用了'pygame.mouse.get_pressed()'。这意味着只要按住鼠标按钮(这意味着即使是常规的点击可能会触发多次),您的“if”和包含的print()也会一遍又一遍地被触发。更好的方法是检查某种'button_released'事件,如果存在?如果没有,你可以自己做:如果按下鼠标按钮,则设置一个布尔值。一旦它不再被按下,你就知道按钮被释放了。 – domsson