如何在pygame中用鼠标移动图片?

How to move an image with the mouse in pygame?

我编写了一个 pygame 小程序,用于通过单击和移动鼠标来移动图像。

我努力使移动函数 movableImg 与我自己的 x, y 参数一起工作,而不是像现在这样与预定义的 x, y 参数一起工作。

这是我的代码:

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

您不需要该功能。您所需要的只是 for 循环中的一些事件。不用乱七八糟的复杂函数,只要点击一下鼠标就可以简单搞定:

for event in pygame.event.get():
    if event.type == MOUSEBUTTONDOWN:    #Remember to use: from pygame.locals import *
        coordinates = pygame.mouse.get_pos()  
        #set x and y to respective values of coordinates
        #Enter necessary code here after

现在coordinates是我在这里编的一个pre-defined变量,在本例中,它是用来存储你鼠标的坐标的。当 event.typeMOUSEBUTTONDOWN 时,表示鼠标已被单击,程序应开始执行该 if 语句下的代码。这些事件只会激活一次,这意味着您不能拖动。我建议您创建一个函数,允许事件在用户像这样按住鼠标时继续:

def holding():
    global held, coordinates
    if held:
        coordinates = pygame.mouse.get_pos()
        #Enter code here

held 将是一个布尔变量:如果鼠标被单击,它将等于 True,否则等于 False。在这种情况下,为防止程序认为您正在无限单击鼠标,请添加另一个 if 语句来检查鼠标是否已被释放,如果是,则将 held 更改为 False

if event.type == MOUSEBUTTONUP:
    held = False

此外,为确保该函数实际记录鼠标仍被按住的事实,将此行放在 MOUSEBUTTONDOWN 事件的 if 语句中:

held = True

最后,对于 运行 函数,在 for 循环前面添加一个 if 语句以在需要时 运行 函数:

if held:
    holding 

要移动多个图像,请将它们的位置更改为等于 coordinates 或与 coordinates 有某种关联。 if 语句不必一次只移动一张图像。

这是我在 Internet 上找到的代码,它可以正常工作。 SOURCE

import os,sys
import pygame as pg #lazy but responsible (avoid namespace flooding)

class Character:
    def __init__(self,rect):
        self.rect = pg.Rect(rect)
        self.click = False
        self.image = pg.Surface(self.rect.size).convert()
        self.image.fill((255,0,0))
    def update(self,surface):
        if self.click:
            self.rect.center = pg.mouse.get_pos()
        surface.blit(self.image,self.rect)

def main(Surface,Player):
    game_event_loop(Player)
    Surface.fill(0)
    Player.update(Surface)


def game_event_loop(Player):
    for event in pg.event.get():
        if event.type == pg.MOUSEBUTTONDOWN:
            if Player.rect.collidepoint(event.pos):
                Player.click = True
        elif event.type == pg.MOUSEBUTTONUP:
            Player.click = False
        elif event.type == pg.QUIT:
            pg.quit(); sys.exit()

if __name__ == "__main__":
    os.environ['SDL_VIDEO_CENTERED'] = '1'
    pg.init()
    Screen = pg.display.set_mode((1000,600))
    MyClock = pg.time.Clock()
    MyPlayer = Character((0,0,150,150))
    MyPlayer.rect.center = Screen.get_rect().center
    while 1:
        main(Screen,MyPlayer)
        pg.display.update()
        MyClock.tick(60)