import pygame from random import randrange from display import Scaling from text import Fonts class EnemySprite(pygame.sprite.Sprite): def __init__(self): super().__init__() self.position = (0, 0) self.movement = (0, 0) def set_position(self, position: tuple): self.position = position self.update() def set_movement(self, movement: tuple): self.movement = movement def update(self, dt = 0, **kwargs): if dt: self.position = ( self.position[0] + self.movement[0] * dt, self.position[1] + self.movement[1] * dt) self.rect = pygame.Rect( Scaling.scale_to_display(self.position), self.image.get_size()) def force_right(self): self.movement = (abs(self.movement[0]), self.movement[1]) def force_left(self): self.movement = (-abs(self.movement[0]), self.movement[1]) def force_down(self): self.movement = (self.movement[0], abs(self.movement[1])) def force_up(self): self.movement = (self.movement[0], -abs(self.movement[1])) class EnemyBall(EnemySprite): def __init__(self): super().__init__() letter = Fonts.fonts['8x8'].get(randrange(1,3)).subsurface((0,0,8,8)) colored = letter.fill( "black", special_flags = pygame.BLEND_RGBA_MULT) self.image = pygame.transform.scale_by(letter, 1_000 * Scaling.factor) self.update() class Enemies(pygame.sprite.Group): def __init__(self, field = None, count = 0): super().__init__() for _ in range(count): enemy = EnemyBall() enemy.set_position( (randrange(0,300_000), randrange(0,200_000)) ) enemy.set_movement( (randrange(0,200)-100, randrange(0,200)-100) ) self.add(enemy) self.field = field def update(self, field_rects = [], **kwargs): super().update(**kwargs) """ Do actions on enemies that are only partly on the fields """ for enemy in self.sprites(): for field_rect in field_rects: # if enemy is completely inside any field do next enemy if field_rect.contains(enemy): break else: # now find field that enemy is partly on for field_rect in field_rects: if field_rect.colliderect(enemy): self.wall_hit(field_rect, enemy) def wall_hit(self, field, enemy): if enemy.rect.x < field.x: enemy.force_right() if enemy.rect.y < field.y: enemy.force_down() if ( enemy.rect.x + enemy.rect.w >= field.x + field.w ): enemy.force_left() if ( enemy.rect.y + enemy.rect.h >= field.y + field.h ): enemy.force_up()