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