From 12319fc1ab72e9b0d32780c36489ca7fca91c6b0 Mon Sep 17 00:00:00 2001 From: LordBaryhobal Date: Sat, 18 Oct 2025 01:30:33 +0200 Subject: [PATCH] feat: add vec class --- src/vec.py | 57 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 src/vec.py diff --git a/src/vec.py b/src/vec.py new file mode 100644 index 0000000..652b7e7 --- /dev/null +++ b/src/vec.py @@ -0,0 +1,57 @@ +from __future__ import annotations + +from math import sqrt + + +class Vec: + def __init__(self, x: float = 0, y: float = 0) -> None: + self.x: float = x + self.y: float = y + + def __add__(self, other: float | Vec) -> Vec: + if isinstance(other, Vec): + return Vec(self.x + other.x, self.y + other.y) + return Vec(self.x + other, self.y + other) + + def __sub__(self, other: float | Vec) -> Vec: + if isinstance(other, Vec): + return Vec(self.x - other.x, self.y - other.y) + return Vec(self.x - other, self.y - other) + + def __mul__(self, value: float) -> Vec: + return Vec(self.x * value, self.y * value) + + def __truediv__(self, value: float) -> Vec: + return Vec(self.x / value, self.y / value) + + def dot(self, other: Vec) -> float: + return self.x * other.x + self.y * other.y + + def mag(self) -> float: + return sqrt(self.mag2()) + + def mag2(self) -> float: + return self.dot(self) + + def cross(self, other: Vec) -> float: + return self.x * other.y - self.y * other.x + + @property + def normalized(self) -> Vec: + mag: float = self.mag() + if mag == 0: + return Vec() + return self / mag + + def __len__(self) -> int: + return 2 + + def __getitem__(self, item): + return [self.x, self.y][item] + + @property + def perp(self) -> Vec: + return Vec(-self.y, self.x) + + def __repr__(self) -> str: + return f"Vec({self.x}, {self.y})"