background_manager.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import pygame
  2. change_speed = 2
  3. class DynamicBackground():
  4. def __init__(self, size):
  5. self.image_loaded = False
  6. self.size = size
  7. self.surface = pygame.Surface(self.size).convert()
  8. self.surface.fill((145, 16, 16))
  9. self.surface_image = pygame.Surface(self.size).convert()
  10. self.update = True
  11. def draw_background(self):
  12. if self.image_loaded:
  13. return self.surface_image.copy()
  14. else:
  15. return self.surface.copy()
  16. def should_update(self):
  17. if self.update:
  18. self.update = False
  19. return True
  20. else:
  21. return False
  22. def set_background_image(self, image):
  23. if image is not None:
  24. image_size = get_aspect_scale_size(image, self.size)
  25. target = pygame.transform.smoothscale(image, image_size)
  26. target.set_alpha(150)
  27. self.image_loaded = True
  28. self.surface_image.fill((0, 0, 0))
  29. pos = ((self.size[0] - image_size[0])/2,
  30. (self.size[1] - image_size[1])/2)
  31. self.surface_image.blit(target, pos)
  32. else:
  33. self.image_loaded = False
  34. self.update = True
  35. def get_aspect_scale_size(img, (bx, by)):
  36. size = img.get_size()
  37. aspect_x = bx / float(size[0])
  38. aspect_y = by / float(size[1])
  39. if aspect_x > aspect_y:
  40. aspect = aspect_x
  41. else:
  42. aspect = aspect_y
  43. new_size = (int(aspect*size[0]), int(aspect*size[1]))
  44. return new_size