transparent_range.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. """Pixel rectangles relative to an obstacle's map-cell origin (not its image)."""
  2. import math
  3. TRANSPARENT_ALPHA = 127
  4. TRANSITION_MS = 180
  5. class AlphaTransition:
  6. """Time-based fade; reversing direction keeps the current opacity."""
  7. def __init__(self):
  8. self.alpha = 255.0
  9. self.target = 255
  10. self.last_time = None
  11. def advance(self, target, now):
  12. if self.last_time is None or target != self.target:
  13. self.target = target
  14. self.last_time = now
  15. return round(self.alpha)
  16. elapsed = max(0, now - self.last_time)
  17. self.last_time = now
  18. step = (255 - TRANSPARENT_ALPHA) * elapsed / TRANSITION_MS
  19. if self.alpha < target:
  20. self.alpha = min(target, self.alpha + step)
  21. else:
  22. self.alpha = max(target, self.alpha - step)
  23. return round(self.alpha)
  24. def fade_height(ranges, image_top, image_height):
  25. """Rows above the lowest bottom edge, accounting for the frame's CY."""
  26. if not ranges:
  27. return 0
  28. bottom = max(r["y2"] for r in ranges)
  29. return max(0, min(image_height, math.ceil(bottom - image_top)))
  30. def normalize_ranges(value):
  31. """Validate and normalize rectangles. None/missing means no transparency."""
  32. if value is None:
  33. return []
  34. if not isinstance(value, list):
  35. raise ValueError("TRANSPARENT_RANGE 必须是矩形列表")
  36. result = []
  37. for index, item in enumerate(value):
  38. if not isinstance(item, dict):
  39. raise ValueError("第 %d 个区域必须是字典" % (index + 1))
  40. coords = []
  41. for key in ("x1", "y1", "x2", "y2"):
  42. number = item.get(key)
  43. if isinstance(number, bool) or not isinstance(number, (int, float)) or not math.isfinite(number):
  44. raise ValueError("第 %d 个区域的 %s 必须是有限数值" % (index + 1, key))
  45. coords.append(number)
  46. x1, y1, x2, y2 = coords
  47. left, right = min(x1, x2), max(x1, x2)
  48. top, bottom = min(y1, y2), max(y1, y2)
  49. if left == right or top == bottom:
  50. raise ValueError("第 %d 个区域的宽和高必须大于 0" % (index + 1))
  51. result.append(dict(x1=left, y1=top, x2=right, y2=bottom))
  52. return result
  53. def contains_point(ranges, x, y):
  54. # Match pygame's left/top-inclusive and right/bottom-exclusive rectangles.
  55. return any(r["x1"] <= x < r["x2"] and r["y1"] <= y < r["y2"] for r in ranges)