1

So here is a simplified version of my code in which I am trying to plot these images using a for loop. But when these images are on the screen they sometimes overlap or touch each other. So what can I do to stop that.

import pygame
import random

win_size = (600, 400)
win = pygame.display.set_mode(win_size, 0, 32)

jumperImg = []
jumperx = []
jumpery = []

for i in range(5):
    jumperImg.append(pygame.image.load("anyimg.png"))
    jumperx.append(random.randint(0,600))
    jumpery.append(50)



def jumper(x, y, i):
    win.blit(jumperImg[i], (x, y))


running = True
while running:
    for event in pygame.event.get():  # event loop
        if event.type == pygame.QUIT:
            running = False

    for i in range(5):
        jumper(jumperx[i], jumpery[i], i)


    pygame.display.update()
Aditya Nambidi
  • 101
  • 2
  • 13

1 Answers1

0

You have to store the rectangular area which is covered by an image to a list. Use pygame.Rect to represent a rectangle. Create a random position for a new image and use collidelist() to evaluate if the new image collides with any other image. If the image collides then skip the position and create a new random position. Use a loop to repeat this process as long the image is colliding:

img = pygame.image.load("anyimg.png")

rect_list = []
for i in range(5):
    collide = 0
    while collide >= 0:
        x, y = random.randint(0,600), 50
        img_rect = img.get_rect(topleft = (x, y))
        collide = img_rect.collidelist(rect_list)

    rect_list.append(img_rect)
    jumperImg.append(img)
    jumperx.append(x)
    jumpery.append(y)
Rabbid76
  • 202,892
  • 27
  • 131
  • 174