A 2 dimensional vector class, used as a helper class for implementing turtle graphics. May be useful for turtle graphics programs also. Derived from tuple, so a vector is a tuple! Provides (for a, b vectors, k number): a+b vector addition a-b vector subtraction
| 132 | |
| 133 | |
| 134 | class Vec2D(tuple): |
| 135 | """A 2 dimensional vector class, used as a helper class |
| 136 | for implementing turtle graphics. |
| 137 | May be useful for turtle graphics programs also. |
| 138 | Derived from tuple, so a vector is a tuple! |
| 139 | |
| 140 | Provides (for a, b vectors, k number): |
| 141 | a+b vector addition |
| 142 | a-b vector subtraction |
| 143 | a*b inner product |
| 144 | k*a and a*k multiplication with scalar |
| 145 | |a| absolute value of a |
| 146 | a.rotate(angle) rotation |
| 147 | """ |
| 148 | def __new__(cls, x, y): |
| 149 | return tuple.__new__(cls, (x, y)) |
| 150 | def __add__(self, other): |
| 151 | return Vec2D(self[0]+other[0], self[1]+other[1]) |
| 152 | def __mul__(self, other): |
| 153 | if isinstance(other, Vec2D): |
| 154 | return self[0]*other[0]+self[1]*other[1] |
| 155 | return Vec2D(self[0]*other, self[1]*other) |
| 156 | def __rmul__(self, other): |
| 157 | if isinstance(other, int) or isinstance(other, float): |
| 158 | return Vec2D(self[0]*other, self[1]*other) |
| 159 | return NotImplemented |
| 160 | def __sub__(self, other): |
| 161 | return Vec2D(self[0]-other[0], self[1]-other[1]) |
| 162 | def __neg__(self): |
| 163 | return Vec2D(-self[0], -self[1]) |
| 164 | def __abs__(self): |
| 165 | return (self[0]**2 + self[1]**2)**0.5 |
| 166 | def rotate(self, angle): |
| 167 | """rotate self counterclockwise by angle |
| 168 | """ |
| 169 | perp = Vec2D(-self[1], self[0]) |
| 170 | angle = angle * math.pi / 180.0 |
| 171 | c, s = math.cos(angle), math.sin(angle) |
| 172 | return Vec2D(self[0]*c+perp[0]*s, self[1]*c+perp[1]*s) |
| 173 | def __getnewargs__(self): |
| 174 | return (self[0], self[1]) |
| 175 | def __repr__(self): |
| 176 | return "(%.2f,%.2f)" % self |
| 177 | |
| 178 | |
| 179 | ############################################################################## |
no outgoing calls
no test coverage detected