Drag'n'Drop
Eine kleine Drag'n'Drop Beispielimplementation in Pygame.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 | """
Pygame Drag'n'Drop Example
"""
import pygame
import pygame.locals as loc
def main():
# standard init stuff
pygame.init()
screen = pygame.display.set_mode((640, 400))
pygame.display.set_caption("pygame drag'n'drop example - by jug")
clock = pygame.time.Clock()
# create a rect as simple object to drag'n'drop
rect = pygame.Rect(10,10,50,50)
# in this variable we will save the offset from the topleft of our rect
# to the mouse pointer
offset = None
# start the mainloop
while 1:
# limit fps to 40
clock.tick(40)
# handle events
for event in pygame.event.get():
# standard events to exit the program
if event.type == loc.QUIT:
return
elif event.type == loc.KEYDOWN:
if event.key == loc.K_ESCAPE:
return
# if a button is pressed above the rect,
# save the offset and start dragging
elif (event.type == loc.MOUSEBUTTONDOWN
and rect.collidepoint(event.pos)):
mouse_x, mouse_y = event.pos
my_x, my_y = rect.topleft
offset = mouse_x - my_x, mouse_y - my_y
# if no button is pressed anymore, stop dragging
# I use mouse.get_pressed and not MOUSEBUTTONUP here to make sure
# we don't lose the mouse release
if not any(pygame.mouse.get_pressed()):
offset = None
# if we have an offset, ie if we are dragging, calculate the new
# position with the current mouse position and our offset
if offset:
mouse_x, mouse_y = pygame.mouse.get_pos()
off_x, off_y = offset
rect.topleft = mouse_x - off_x, mouse_y - off_y
# fill the screen, draw the rect and flip it
screen.fill((200,200,200))
screen.fill((0,0,0), rect)
pygame.display.flip()
if __name__ == '__main__': main()
|
erstellt am 25.10.2009 11:38, zuletzt gendert am 25.10.2009 11:40
