Skip to content

Instantly share code, notes, and snippets.

@fitoria
Created October 28, 2015 22:10
Show Gist options
  • Save fitoria/ea795ef8f41f17b1d52c to your computer and use it in GitHub Desktop.
Save fitoria/ea795ef8f41f17b1d52c to your computer and use it in GitHub Desktop.
ejemplo de arrastre con pygame
import pygame
import sys
OLPC_SCREEN_SIZE = (640, 480)
BLANCO = (255, 255, 255)
AZUL = (0, 0, 255)
AMARILLO = (255, 255, 0)
class Main(object):
screen = None
def run(self):
pygame.init()
self.screen = pygame.display.set_mode(OLPC_SCREEN_SIZE)
self.fondo = pygame.Surface(OLPC_SCREEN_SIZE)
self.fondo.fill(BLANCO)
self.screen.blit(self.fondo, (0,0))
cuadro_azul = pygame.Surface((50, 50))
cuadro_azul.fill(AZUL)
rect_azul = cuadro_azul.get_rect()
rect_azul.top = 20
rect_azul.left = 20
cuadro_amarillo = pygame.Surface((100, 100))
cuadro_amarillo.fill(AMARILLO)
rect_amarillo = cuadro_amarillo.get_rect()
rect_amarillo.top = 300
rect_amarillo.left = 300
self.screen.blit(cuadro_azul, (20, 20))
self.screen.blit(cuadro_amarillo, (300, 300))
pygame.display.update()
arrastrar_azul = False
pos_inicial = None
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit(0)
if event.type == pygame.MOUSEBUTTONDOWN:
#(x, y)
pos = pygame.mouse.get_pos()
colisiona_amarillo = rect_amarillo.contains(rect_azul)
if arrastrar_azul and colisiona_amarillo:
#dibujar el azul dentro del amarillo
self.screen.blit(cuadro_amarillo, (300, 300))
self.screen.blit(cuadro_azul, pos)
pygame.display.update()
arrastrar_azul = False
continue
if rect_azul.collidepoint(pos):
arrastrar_azul = True
pos_inicial = pos
self.screen.blit(self.fondo, (20, 20), rect_azul)
else:
arrastrar_azul = False
if event.type == pygame.MOUSEMOTION:
if arrastrar_azul:
pos = pygame.mouse.get_pos()
colisiona_amarillo = rect_amarillo.contains(rect_azul)
if pos_inicial and not colisiona_amarillo:
#la que hace el truco
self.screen.blit(self.fondo, pos_inicial, rect_azul)
self.screen.blit(cuadro_amarillo, (300, 300))
rect_azul.left, rect_azul.top = pos
self.screen.blit(cuadro_azul, rect_azul)
pos_inicial = pos
pygame.display.update()
if __name__ == "__main__":
Main().run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment