So verschieben Sie ein Bild mit der Maus in pygame?

Ich geschrieben habe, ein wenig pygame Programm für das verschieben eines Bildes durch klicken und bewegen der Maus.

Kämpfe ich mit der verschieben-Funktion movableImg Arbeit mit meinen eigenen x, y Parameter und nicht mit den vordefinierten x, y Parameter, wie es jetzt ist.

Hier ist mein code:

import pygame
import time

pygame.init()

display_width = 800
display_height = 600

white = (255, 255, 255)

gameDisplay = pygame.display.set_mode((display_width, display_height))
clock = pygame.time.Clock()

drag = 0    #switch with which I am seting if I can move the image
x = 100   #x, y coordinates of the image
y = 100

img = pygame.image.load('button.png')   #my image and then his width and height
imgWidth = 100
imgHeight = 100


def image(imgX,imgY):   #function to blit image easier
    gameDisplay.blit(img, (imgX, imgY))


def movableImg():   #function in which i am moving image
    global drag, x, y
    mouse = pygame.mouse.get_pos()
    click = pygame.mouse.get_pressed()

    image(x, y)

    if click[0] == 1 and x + imgWidth > mouse[0] > x and y + imgHeight > mouse[1] > y:  #asking if i am within the boundaries of the image
        drag = 1                                                                        #and if the left button is pressed

    if click[0] == 0:   #asking if the left button is pressed
        drag = 0

    if drag == 1:   #moving the image
        x = mouse[0] - (imgWidth / 2)   #imgWidth /2 because i want my mouse centered on the image
        y = mouse[1] - (imgHeight / 2)


def main_loop():
    while True:        
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()

        gameDisplay.fill(white)

        movableImg()

        pygame.display.update()
        clock.tick(60)

main_loop()
pygame.quit()
quit()
"global drag, x, y" jedes mal, wenn Sie die global Stichwort.. nicht. Es gibt bessere Wege, das zu tun.
Ja, ich denke u r Recht.... Ich denke, ich werde einfach versuchen, an etwas zu denken besser... E: So ist es wohl besser, wenn ich einfach weitere Funktionen anstelle von globalen Variablen?
pass-Eingang und Ausgang zu/von Ihrer Funktion über Parameter und Rückgabewerte.
vielen Dank für die Hilfe und Ratschläge

InformationsquelleAutor mikro45 | 2016-01-04

Schreibe einen Kommentar