How can I drag more than 2 images in PyGame?

Create a list of 4 images:

images = [img1, img2, img3, img4]

Create a list of image rectangles:

img_rects = [images[i].get_rect(topleft = (20+40*i, 20)) for i in range(len(images))]

Use pygame.Rect.collidelist to find the image which is clicked:

if e.type == pygame.MOUSEBUTTONDOWN:
    mouse_rect = pygame.Rect(e.pos, (1, 1))
    current_image = mouse_rect.collidelist(img_rects)

Draw the current_image:

if e.type == MOUSEMOTION:
    if e.buttons[LeftButton]:
        rel = e.rel
        if 0 <= current_image < len(images):
            img_rects[current_image].x += rel[0]
            img_rects[current_image].y += rel[1]

Draw the images in a loop:

for i in range(len(images)):
    screen.blit(imgages[i], img_rects[i])

Minimal example:

import pygame
from pygame.locals import *

pygame.display.init()
screen = pygame.display.set_mode((1143, 677))

img1 = pygame.image.load(r"C:\Users\ga-sa\Downloads\As.png")
img2 = pygame.image.load(r"C:\Users\ga-sa\Downloads\03.png")
img3 = pygame.image.load(r"C:\Users\ga-sa\Downloads\As.png")
img4 = pygame.image.load(r"C:\Users\ga-sa\Downloads\03.png")

images = [img1, img2, img3, img4]

current_image = -1
img_rects = [images[i].get_rect(topleft = (20+40*i, 20)) for i in range(len(images))]

LeftButton = 0
while 1:
    for e in pygame.event.get():
        if e.type == QUIT:
            pygame.quit()
            exit(0)

        if e.type == pygame.MOUSEBUTTONDOWN:
            mouse_rect = pygame.Rect(e.pos, (1, 1))
            current_image = mouse_rect.collidelist(img_rects)

        if e.type == MOUSEMOTION:
            if e.buttons[LeftButton]:
                rel = e.rel
                if 0 <= current_image < len(images):
                    img_rects[current_image].x += rel[0]
                    img_rects[current_image].y += rel[1]

    screen.fill(0)
    for i in range(len(images)):
        screen.blit(images[i], img_rects[i])
    pygame.display.flip()
    pygame.time.delay(30)

Leave a Comment