"""Pixel rectangles relative to an obstacle's map-cell origin (not its image).""" import math TRANSPARENT_ALPHA = 127 TRANSITION_MS = 180 class AlphaTransition: """Time-based fade; reversing direction keeps the current opacity.""" def __init__(self): self.alpha = 255.0 self.target = 255 self.last_time = None def advance(self, target, now): if self.last_time is None or target != self.target: self.target = target self.last_time = now return round(self.alpha) elapsed = max(0, now - self.last_time) self.last_time = now step = (255 - TRANSPARENT_ALPHA) * elapsed / TRANSITION_MS if self.alpha < target: self.alpha = min(target, self.alpha + step) else: self.alpha = max(target, self.alpha - step) return round(self.alpha) def fade_height(ranges, image_top, image_height): """Rows above the lowest bottom edge, accounting for the frame's CY.""" if not ranges: return 0 bottom = max(r["y2"] for r in ranges) return max(0, min(image_height, math.ceil(bottom - image_top))) def normalize_ranges(value): """Validate and normalize rectangles. None/missing means no transparency.""" if value is None: return [] if not isinstance(value, list): raise ValueError("TRANSPARENT_RANGE 必须是矩形列表") result = [] for index, item in enumerate(value): if not isinstance(item, dict): raise ValueError("第 %d 个区域必须是字典" % (index + 1)) coords = [] for key in ("x1", "y1", "x2", "y2"): number = item.get(key) if isinstance(number, bool) or not isinstance(number, (int, float)) or not math.isfinite(number): raise ValueError("第 %d 个区域的 %s 必须是有限数值" % (index + 1, key)) coords.append(number) x1, y1, x2, y2 = coords left, right = min(x1, x2), max(x1, x2) top, bottom = min(y1, y2), max(y1, y2) if left == right or top == bottom: raise ValueError("第 %d 个区域的宽和高必须大于 0" % (index + 1)) result.append(dict(x1=left, y1=top, x2=right, y2=bottom)) return result def contains_point(ranges, x, y): # Match pygame's left/top-inclusive and right/bottom-exclusive rectangles. return any(r["x1"] <= x < r["x2"] and r["y1"] <= y < r["y2"] for r in ranges)