dynamic_background.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import random
  2. change_speed = 2
  3. class DynamicBackground():
  4. def __init__(self):
  5. self.current = get_valid_color()
  6. self.target = get_valid_color()
  7. self.auto_mode = True
  8. self.target_current_same = False
  9. def draw_background(self, surfaces):
  10. if not self.target_current_same:
  11. for x in range(0, 3):
  12. if abs(self.current[x]-self.target[x]) < change_speed:
  13. self.current[x] = self.target[x]
  14. self.target_current_same = True
  15. else:
  16. self.target_current_same = False
  17. if self.current[x] > self.target[x]:
  18. self.current[x] -= change_speed
  19. elif self.current[x] < self.target[x]:
  20. self.current[x] += change_speed
  21. if self.auto_mode and self.target_current_same:
  22. self.target = get_valid_color()
  23. self.target_current_same = False
  24. for surface in surfaces:
  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