dynamic_background.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import random
  2. import logging
  3. change_speed = 2
  4. class DynamicBackground():
  5. def __init__(self):
  6. self.current = get_valid_color()
  7. self.target = get_valid_color()
  8. self.auto_mode = True
  9. self.target_current_same = False
  10. def draw_background(self, surface):
  11. if not self.target_current_same:
  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. self.target_current_same = True
  16. else:
  17. self.target_current_same = False
  18. if self.current[x] > self.target[x]:
  19. self.current[x] -= change_speed
  20. elif self.current[x] < self.target[x]:
  21. self.current[x] += change_speed
  22. if self.auto_mode and self.target_current_same:
  23. self.target = get_valid_color()
  24. self.target_current_same = False
  25. surface.fill(self.current)
  26. def set_target_color(self, color):
  27. if color is not None:
  28. self.auto_mode = False
  29. self.target_current_same = False
  30. self.target = get_similar_valid_color(color)
  31. else:
  32. self.auto_mode = True
  33. self.target = get_valid_color()
  34. self.target_current_same = False
  35. # It will return the same color if sum is less than 510
  36. # Otherwise a darker color will be returned
  37. # White text should be seen ok with this background color
  38. def get_similar_valid_color(color):
  39. sum = color[0] + color[1] + color[2]
  40. new_color = [0, 0, 0]
  41. if sum > 510:
  42. rest = (sum - 510)/3 + 1
  43. for x in range(0,3):
  44. new_color[x] = color[x] - rest
  45. return new_color
  46. else:
  47. return color
  48. # Returns an array with 3 integers in range of 0-255
  49. # The sum of the three integers will be lower than 255*2
  50. # (510) to avoid very bright colors
  51. # White text should be seen ok with this background color
  52. def get_valid_color():
  53. color = [0, 0, 0]
  54. total = 0
  55. for i in range(0, 3):
  56. color[i] = random.randint(0, 255)
  57. total += color[i]
  58. extra = total - 510
  59. if extra > 0:
  60. i = random.randint(0, 2)
  61. color[i] -= extra
  62. return color