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
« prev ^ index » next coverage.py v7.16.2, created at 2026-12-04 00:01 +0000
1from dataclasses import dataclass
2from math import isqrt
4from retrospeedlab.games.tiltknight.tuning import BALL_RADIUS, SUB, UNIT
6Point = tuple[int, int]
7Solid = tuple[int, int, int, int, int, int, int, int]
10@dataclass(slots=True, frozen=True)
11class Segment:
12 start: Point
13 end: Point
14 kind: int
15 index: int
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
23 def middle(self) -> Point:
24 return (self.start[0] + self.end[0]) // 2, (self.start[1] + self.end[1]) // 2
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)
31@dataclass(slots=True, frozen=True)
32class Circle:
33 center: Point
34 radius: int
35 kind: int
36 index: int
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
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
47Shape = Segment | Circle
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:]))
54def mirror_point(point: Point, middle: int) -> Point:
55 return 2 * middle - point[0], point[1]
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)
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
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