0

Whenever I click on the square once, it prints the text "You have opened a chest!" numerous times, but I want the program to only print it once per click even if I hold the mouse button in. What do I adjust or add in?

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

Please also give me the adjusted code; that would be highly appreciated. Thanks in advance!

  • I don't know pygame, but usually there is a `released` event in addition to the `pressed` event. Try checking for that instead. – domsson Mar 06 '17 at 15:23
  • I would suggest a latch of some sort. Say you have an array of chests, each chest has its coordinates and contents as well as if its opened or not. So if Rectplace.collidepoint(pos) and pressed1 == 1 and chest.opened == False: – Gauthier Mar 06 '17 at 15:24
  • I just noticed that you are using `pygame.mouse.get_pressed()` in your loop. That means your `if` and the contained `print()` will be triggered over and over again, as long as you hold the mouse button down (which means that even a regular click will probably trigger several times). A better approach is to check for some kind of `button_released` event, if that exists? If not, you could do it yourself: set a boolean if the mouse button is pressed. Once it isn't pressed anymore, you know the button was released. – domsson Mar 06 '17 at 15:31
  • Possible duplicate of [Pygame mouse clicking detection](http://stackoverflow.com/questions/10990137/pygame-mouse-clicking-detection) – domsson Mar 06 '17 at 15:32

1 Answers1

0

Try changing the value of pressed1 to 0 , right after the print line , pressed1 = 0

Yuval
  • 180
  • 13