-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvector.py
More file actions
125 lines (94 loc) · 2.2 KB
/
vector.py
File metadata and controls
125 lines (94 loc) · 2.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
from math import sqrt
class Vector2:
def __init__(self, x=0, y=0):
if isinstance(x, (tuple, list)):
x, y = x
elif isinstance(x, Vector2):
x, y = x.tuple()
self.x = x
self.y = y
def tuple(self, t=float):
return t(self.x), t(self.y)
def copy(self):
return Vector2(self.x, self.y)
def __str__(self):
return f'({self.x},{self.y})'
@staticmethod
def to_vector(other):
if isinstance(other, (int, float)):
return Vector2(other, other)
return Vector2(other)
def __add__(self, other):
v = self.copy()
v += other
return v
def __radd__(self, other):
return self + other
def __iadd__(self, other):
other = Vector2.to_vector(other)
self.x += other.x
self.y += other.y
return self
def __sub__(self, other):
return self + (-other)
def __rsub__(self, other):
return other + (-self)
def __isub__(self, other):
other = Vector2(other) if isinstance(other, (list, tuple)) else other
self += -other
return self
def __mul__(self, other):
v = self.copy()
v *= other
return v
def __rmul__(self, other):
if isinstance(other, (int, float)):
return other * min(self.x, self.y)
return self * other
def __imul__(self, other):
other = Vector2.to_vector(other)
self.x *= other.x
self.y *= other.y
return self
def __truediv__(self, other):
v = self.copy()
v /= other
return v
def __rtruediv__(self, other):
v = self.copy()
v.x = 1 / v.x
v.y = 1 / v.y
return other * v
def __itruediv__(self, other):
other = Vector2.to_vector(other)
self.x /= other.x
self.y /= other.y
return self
def __floordiv__(self, other):
v = self.copy()
v //= other
return v
def __rfloordiv__(self, other):
v = self.copy()
v.x = 1 // v.x
v.y = 1 // v.y
return other * v
def __ifloordiv__(self, other):
other = Vector2.to_vector(other)
self.x //= other.x
self.y //= other.y
return self
def __neg__(self):
return Vector2(-self.x, -self.y)
def __pos__(self):
return Vector2(+self.x, +self.y)
def __abs__(self):
return sqrt(self.mag_sq())
def mag_sq(self):
return self.x ** 2 + self.y ** 2
Vector2.zero = Vector2()
Vector2.one = Vector2(1, 1)
if __name__ == "__main__":
v1 = Vector2(1, 2)
v2 = Vector2(2, 1)
print(v1 // v2)