dynamic_background.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import random
  2. change_speed = 2
  3. import pygame
  4. class DynamicBackground():
  5. def __init__(self, size):
  6. self.size = size
  7. self.current = get_valid_color()
  8. self.target = get_valid_color()
  9. self.surface = None
  10. def draw_background(self, surface):
  11. same = True
  12. for x in range(0, 3):
  13. if abs(self.current[x]-self.target[x]) < change_speed:
  14. self.current[x] = self.target[x]
  15. else:
  16. if self.current[x] > self.target[x]:
  17. self.current[x] -= change_speed
  18. elif self.current[x] < self.target[x]:
  19. self.current[x] += change_speed
  20. if self.current != self.target:
  21. same = False
  22. #if same:
  23. # self.target = get_valid_color()
  24. surface.fill(self.current)
  25. if self.surface is not None:
  26. surface.blit(self.surface,(0,0))
  27. def set_target_color(self, color, surface):
  28. self.target = [color[0], color[1], color[2]]
  29. #irudi = pygame.Surface(surface.get_size())
  30. #pygame.transform.laplacian(surface, irudi)
  31. irudi = surface
  32. target = pygame.Surface(self.size)
  33. pygame.transform.smoothscale(irudi, self.size, target)
  34. target.set_alpha(80)
  35. self.surface = target
  36. # Returns an array with 3 integers in range of 0-255
  37. # The sum of the three integers will be lower than 255*2
  38. # (510) to avoid very bright colors
  39. # White text should be seen ok with this background color
  40. def get_valid_color():
  41. color = [0, 0, 0]
  42. total = 0
  43. for i in range(0, 3):
  44. color[i] = random.randint(0, 255)
  45. total += color[i]
  46. extra = total - 510
  47. if extra > 0:
  48. i = random.randint(0, 2)
  49. color[i] -= extra
  50. return color