I'm trying to add to my platformer with some PVP mechanics. The first thing I decided to do is to add a generation of enemies. After creating an Enemy class and a function to create a list with enemies' information, I started my test by trying to blit my enemies to the screen, but the problem is that sometimes they blit once, and sometimes they don't blit at all. Sometimes they blit 50% of the time. Why? Here are all parts of the code that retouch enemies generation and display.
def generate_enemy(player, enemy_group, image_list):
for i in range(3):
enemy = Enemy(player, image_list)
enemy_group.add(enemy)
class Player(pygame.sprite.Sprite):
def __init__(self, x, y, image):
super().__init__()
self.image = image
self.x = x
self.y = y
self.width = self.image.get_width()
self.height = self.image.get_height()
self.hitbox = pygame.Rect(self.x, self.y, self.width, self.height)
self.momentum = 0
self.speed = 7
self.health = 100
self.moving_left = False
self.moving_right = False
class Enemy(pygame.sprite.Sprite):
def __init__(self, player, image_list):
super().__init__()
self.image = image_list[0]
self.spawn = []
if random.randint(0, 1) == 1:
self.x = player.hitbox.x + random.randint(50, 60)
self.spawn.append(player.hitbox.x + random.randint(50, 60))
else:
self.x = player.hitbox.x - random.randint(50, 60)
self.spawn.append(player.hitbox.x - random.randint(50, 60))
self.y = player.hitbox.y
self.width = self.image.get_width()
self.height = self.image.get_height()
self.hitbox = pygame.Rect(self.x, self.y, self.width, self.height)
self.momentum = 0
self.speed = random.randint(3,6)
self.health = 50
self.moving_left = False
self.moving_right = False
WINDOW_WIDTH, WINDOW_HEIGHT = 1300, 650
FPS = 60
Enemy_animations = [pygame.transform.scale(pygame.image.load(os.path.join("images\\enemy_animation\\enemy_0.png")).convert_alpha(), (64, 47)),
pygame.transform.scale(pygame.image.load(os.path.join("images\\enemy_animation\\enemy_1.png")).convert_alpha(), (64, 47)),
pygame.transform.scale(pygame.image.load(os.path.join("images\\enemy_animation\\enemy_2.png")).convert_alpha(), (57, 90)),
pygame.transform.scale(pygame.image.load(os.path.join("images\\enemy_animation\\enemy_3.png")).convert_alpha(), (72, 51)),
pygame.transform.scale(pygame.image.load(os.path.join("images\\enemy_animation\\enemy_4.png")).convert_alpha(), (87, 57))]
Enemy_Group = pygame.sprite.Group()
Slid = Player(0, 0, Slid_Current_Image)
display.blit(Slid_Current_Image, (Slid.hitbox.x - scroll[0], Slid.hitbox.y - scroll[1]))
for enemy in Enemy_Group:
display.blit(enemy.image, (enemy.hitbox.x, enemy.hitbox.y))
if frame_counter % 300 == 0:
generate_enemy(Slid, Enemy_Group, Enemy_animations)
surface = pygame.transform.scale(display, (WINDOW_WIDTH, WINDOW_HEIGHT))
window.blit(surface, (0, 0))