If statement 我想阻止这一切';if语句';避免重复

If statement 我想阻止这一切';if语句';避免重复,if-statement,printing,click,python-3.4,If Statement,Printing,Click,Python 3.4,每当我点击方块一次,它就会多次打印文本“You have opened a cost!”,但我希望程序每次点击只打印一次,即使我按住鼠标键。我应该调整或添加什么 import pygame pygame.init() pygame.display.set_caption('Crash!') window = pygame.display.set_mode((300, 300)) running = True #Draw Once Rectplace = pygame.draw.rect(wi

每当我点击方块一次,它就会多次打印文本“You have opened a cost!”,但我希望程序每次点击只打印一次,即使我按住鼠标键。我应该调整或添加什么

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

请同时给我调整后的代码;我们将非常感谢。提前谢谢

在打印行之后,尝试将pressed1的值更改为0,
pressed1=0

我不知道pygame,但通常除了
pressed
事件外,还有一个
released
事件。试着检查一下。我建议用某种门闩。假设你有一个箱子数组,每个箱子都有它的坐标和内容,以及它是否打开。因此,如果Rectplace.collidepoint(pos)并按1==1和cost.opened==False:我刚刚注意到您在循环中使用了
pygame.mouse.get_pressed()
。这意味着只要按住鼠标按钮,您的
if
和包含的
print()
将被一次又一次地触发(这意味着即使是常规的单击也可能会触发多次)。更好的方法是检查某种类型的
按钮\u释放的
事件(如果存在)?如果没有,您可以自己做:如果按下鼠标按钮,则设置一个布尔值。一旦它不再被按下,你就知道按钮被释放了。可能是重复的谢谢,但要么它不工作,要么我把事情搞砸了。不过,我敢打赌我打对了。