vector.py
1 import math 2 3 4 def deg2rad(angle: float) -> float: 5 return (angle % 360) / 180 * math.pi 6 7 8 def rad2deg(angle: float) -> float: 9 return (angle * 180 / math.pi) % 360 10 11 12 class Point: 13 def __init__(self, x: float, y: float): 14 self.x = x 15 self.y = y 16 17 def __repr__(self) -> str: 18 return f"Point(x={self.x}, y={self.y})" 19 20 def __iter__(self): 21 yield self.x 22 yield self.y 23 24 def __add__(self, other): 25 assert isinstance(other, Point) 26 return Point(self.x + other.x, self.y + other.y) 27 28 def __sub__(self, other): 29 assert isinstance(other, Point) 30 return Point(self.x - other.x, self.y - other.y) 31 32 def __mul__(self, other): 33 assert isinstance(other, int) or isinstance(other, float) 34 return Point(self.x * other, self.y * other) 35 36 def __truediv__(self, other): 37 assert isinstance(other, int) or isinstance(other, float) 38 return Point(self.x / other, self.y / other) 39 40 def to_vector(self): 41 if not self.x: return Vector(-self.y, 0) 42 a = math.atan(self.y / self.x) 43 d = self.x / math.cos(a) 44 return Vector(d, rad2deg(a) + 90) 45 46 47 class Vector: 48 def __init__(self, distance: float, angle: float): 49 if distance < 0: 50 distance *= -1 51 angle += 180 52 self.distance = distance 53 self.angle = angle % 360 54 55 def __repr__(self) -> str: 56 return f"Vector(distance={self.distance}, angle={self.angle})" 57 58 def __add__(self, other): 59 assert isinstance(other, Vector) 60 return (self.to_point() + other.to_point()).to_vector() 61 62 def __sub__(self, other): 63 assert isinstance(other, Vector) 64 return (self.to_point() - other.to_point()).to_vector() 65 66 def __mul__(self, other): 67 assert isinstance(other, int) or isinstance(other, float) 68 return Point(self.distance * other, self.angle) 69 70 def __truediv__(self, other): 71 assert isinstance(other, int) or isinstance(other, float) 72 return Point(self.distance / other, self.angle) 73 74 def to_point(self): 75 return Point( 76 math.cos(deg2rad(self.angle - 90)) * self.distance, 77 math.sin(deg2rad(self.angle - 90)) * self.distance 78 ) 79 80 def copy(self): 81 return Vector(self.distance, self.angle)