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: 42 return Vector(-self.y, 0) 43 a = math.atan(self.y / self.x) 44 d = self.x / math.cos(a) 45 return Vector(d, rad2deg(a) + 90) 46 47 48 class Vector: 49 def __init__(self, distance: float, angle: float): 50 if distance < 0: 51 distance *= -1 52 angle += 180 53 self.distance = distance 54 self.angle = angle % 360 55 56 def __repr__(self) -> str: 57 return f"Vector(distance={self.distance}, angle={self.angle})" 58 59 def __add__(self, other): 60 assert isinstance(other, Vector) 61 return (self.to_point() + other.to_point()).to_vector() 62 63 def __sub__(self, other): 64 assert isinstance(other, Vector) 65 return (self.to_point() - other.to_point()).to_vector() 66 67 def __mul__(self, other): 68 assert isinstance(other, int) or isinstance(other, float) 69 return Point(self.distance * other, self.angle) 70 71 def __truediv__(self, other): 72 assert isinstance(other, int) or isinstance(other, float) 73 return Point(self.distance / other, self.angle) 74 75 def to_point(self): 76 return Point( 77 math.cos(deg2rad(self.angle - 90)) * self.distance, 78 math.sin(deg2rad(self.angle - 90)) * self.distance 79 )