[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]

Re: [pygame] Help - Events



I made a little example of drag and drop, not sure if you want that.

# CC0 1.0 Universal
# http://creativecommons.org/publicdomain/zero/1.0/

from sys import exit
from pygame.locals import *
import pygame
pygame.init()

screen = pygame.display.set_mode((640, 480))
clock  = pygame.time.Clock()

# create the rect to drag&drop, center it on the screen
rect = pygame.Rect(0, 0, 100, 100)
rect.center = screen.get_rect().center

draging = None

while True:
   clock.tick(30)
   for e in pygame.event.get():
       if e.type == QUIT:
           pygame.quit()
           exit()
       elif e.type == MOUSEBUTTONDOWN:
           if e.button == 1:
               if draging is None:
if rect.collidepoint(e.pos): # make sure you actually hover the rect draging = (rect.centerx-e.pos[0], rect.centery-e.pos[1])
               else:
                   draging = None
elif e.type == MOUSEMOTION:
           if draging is not None:
               rect.centerx = e.pos[0] + draging[0]
               rect.centery = e.pos[1] + draging[1]
screen.fill((255, 255, 255))
   pygame.draw.rect(screen, (0, 0, 200), rect)
   pygame.display.flip()

# end of CC0 1.0 Universal

Thiago Petruccelli schrieb:
Hi!

I am making a game in wich the player has to fill an area with tiles. It's an educational game. But I got a problem with pygame events... Actually I think it's a simple problem, but I don't know how to solve.

There are two functionalities for the left click of the mouse: the first is to put a tile in the area, when dragging one tile, and the other is to remove one tile of the area (when not dragging). The problem is that, when I put both codes together, the two things happen at the same time - it puts the tile and then removes it. I've tried to block the removal of the tile setting a variable, "placed", which blocks the action of removing the tile until the next event handling. But it didn't work.

Can someone help me solve this?

Thanks in advance,
--
Thiago Henrique Petruccelli