Coverage for src/retrospeedlab/games/tiltknight/geometry.py: 96%

55 statements  

« prev     ^ index     » next       coverage.py v7.16.2, created at 2026-12-04 00:01 +0000

1from dataclasses import dataclass 

2from math import isqrt 

3 

4from retrospeedlab.games.tiltknight.tuning import BALL_RADIUS, SUB, UNIT 

5 

6Point = tuple[int, int] 

7Solid = tuple[int, int, int, int, int, int, int, int] 

8 

9 

10@dataclass(slots=True, frozen=True) 

11class Segment: 

12 start: Point 

13 end: Point 

14 kind: int 

15 index: int 

16 

17 def solid(self) -> Solid: 

18 dx, dy = (self.end[0] - self.start[0]) * SUB, (self.end[1] - self.start[1]) * SUB 

19 length = isqrt(dx * dx + dy * dy) 

20 x, y = self.start[0] * SUB, self.start[1] * SUB 

21 return self.kind, self.index, x, y, dx * UNIT // length, dy * UNIT // length, length, BALL_RADIUS * SUB 

22 

23 def middle(self) -> Point: 

24 return (self.start[0] + self.end[0]) // 2, (self.start[1] + self.end[1]) // 2 

25 

26 def bounds(self) -> tuple[int, int, int, int]: 

27 (x1, y1), (x2, y2) = self.start, self.end 

28 return min(x1, x2), min(y1, y2), max(x1, x2), max(y1, y2) 

29 

30 

31@dataclass(slots=True, frozen=True) 

32class Circle: 

33 center: Point 

34 radius: int 

35 kind: int 

36 index: int 

37 

38 def solid(self) -> Solid: 

39 x, y = self.center[0] * SUB, self.center[1] * SUB 

40 return self.kind, self.index, x, y, 0, 0, 0, (BALL_RADIUS + self.radius) * SUB 

41 

42 def bounds(self) -> tuple[int, int, int, int]: 

43 x, y, r = self.center[0], self.center[1], self.radius 

44 return x - r, y - r, x + r, y + r 

45 

46 

47Shape = Segment | Circle 

48 

49 

50def chain(points: tuple[Point, ...], kind: int) -> tuple[Segment, ...]: 

51 return tuple(Segment(start, end, kind, 0) for start, end in zip(points, points[1:])) 

52 

53 

54def mirror_point(point: Point, middle: int) -> Point: 

55 return 2 * middle - point[0], point[1] 

56 

57 

58def mirrored(shape: Shape, middle: int) -> Shape: 

59 if isinstance(shape, Circle): 

60 return Circle(mirror_point(shape.center, middle), shape.radius, shape.kind, shape.index) 

61 return Segment(mirror_point(shape.start, middle), mirror_point(shape.end, middle), shape.kind, shape.index) 

62 

63 

64def nearest(x: int, y: int, solid: Solid) -> tuple[int, int, int]: 

65 ax, ay, ux, uy, length = solid[2], solid[3], solid[4], solid[5], solid[6] 

66 along = max(0, min(length, ((x - ax) * ux + (y - ay) * uy) // UNIT)) 

67 return ax + ux * along // UNIT, ay + uy * along // UNIT, along 

68 

69 

70def outward(x: int, y: int, spot: Point, reach: int) -> Point | None: 

71 dx, dy = x - spot[0], y - spot[1] 

72 squared = dx * dx + dy * dy 

73 if squared >= reach * reach: 

74 return None 

75 distance = isqrt(squared) 

76 if not distance: 

77 return 0, -UNIT 

78 return dx * UNIT // distance, dy * UNIT // distance