background_manager.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. self.surface_image.fill((0, 0, 0))
  27. pos = (int((self.size[0] - image_size[0])/2),
  28. (int(self.size[1] - image_size[1])/2))
  29. self.surface_image.blit(blur_surf_times(
  30. target, self.size[0]/40, 10), pos)
  31. self.image_loaded = True
  32. else:
  33. self.image_loaded = False
  34. self.update = True
  35. def get_aspect_scale_size(img, new_size):
  36. size = img.get_size()
  37. aspect_x = new_size[0] / float(size[0])
  38. aspect_y = new_size[1] / 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
  45. def blur_surf_times(surface, amt, times):
  46. for i in range(times):
  47. surface = blur_surf(surface, amt)
  48. return surface
  49. # http://www.akeric.com/blog/?p=720
  50. def blur_surf(surface, amt):
  51. """
  52. Blur the given surface by the given 'amount'. Only values 1 and greater
  53. are valid. Value 1 = no blur.
  54. """
  55. scale = 1.0/float(amt)
  56. surf_size = surface.get_size()
  57. scale_size = (int(surf_size[0]*scale), int(surf_size[1]*scale))
  58. surf = pygame.transform.smoothscale(surface, scale_size)
  59. surf = pygame.transform.smoothscale(surf, surf_size)
  60. return surf