dynamic_background.py 2.3 KB

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