0

For some reason, my enemy objects start clumping together in one bar even though they have an acceleration added to them. They are supposed to fall and then disappear but they don't. P.S: I was using lists for the Rect part. I just switched the list to a Rect and it broke. Code:

import pygame, sys, random
pygame.init()
SCREEN_RES = sw, sh = 500, 500
SCREEN = pygame.display.set_mode(SCREEN_RES)
GAME_STATE = True
BACKGROUND = (255, 255, 255)
ENTITIES = []

while GAME_STATE:
    SCREEN.fill(BACKGROUND)
    for i in pygame.event.get():
        if i.type == pygame.QUIT:
           sys.exit()
    ENTITY_RECT = pygame.Rect(random.randint(0, 475), -25, 25, 25)
    ENTITIES.append(ENTITY_RECT)
    for i in ENTITIES:
        pygame.draw.rect(SCREEN, (0), i)
        if i.y != 525:
           i.y += 0.2
        else:
           ENTITIES.remove(i)

pygame.display.flip()
Rabbid76
  • 202,892
  • 27
  • 131
  • 174
lef
  • 1
  • 3

1 Answers1

0

Since pygame.Rect is supposed to represent an area on the screen, a pygame.Rect object can only store integral data.

The coordinates for Rect objects are all integers. [...]

The fraction part of the coordinates gets lost when the movement is added to the y coordinate:

i.y += 0.2

If you want to store object positions with floating point accuracy, you have to store the location of the object in separate variables respectively attributes and to synchronize the pygame.Rect object. round the coordinates and assign it to the location (e.g. .topleft) of the rectangle:

x, y = # floating point coordinates
rect.topleft = round(x), round(y)

Create a list of floating point x and y coordinates rather than a list of rectangles.
Furthermore see How to remove items from a list while iterating?.

import pygame, sys, random
pygame.init()
SCREEN_RES = sw, sh = 500, 500
SCREEN = pygame.display.set_mode(SCREEN_RES)
game_state = True
BACKGROUND = (255, 255, 255)
entities = []

clock = pygame.time.Clock()
while game_state:
    clock.tick(100)
    for i in pygame.event.get():
        if i.type == pygame.QUIT:
            game_state = False

    entities.append([random.randint(0, 475), 0])
    
    SCREEN.fill(BACKGROUND)
    for pos in entities[:]:
        rect = pygame.Rect(*pos, 25, 25)
        pygame.draw.rect(SCREEN, (0), rect)
        if pos[1] != 525:
           pos[1] += 0.2
        else:
           entities.remove(pos)

    pygame.display.flip()

pygame.quit()
sys.exit()
Rabbid76
  • 202,892
  • 27
  • 131
  • 174