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
| 231 | |
| 232 | |
| 233 | class Vec2D(tuple): |
| 234 | """A 2 dimensional vector class, used as a helper class |
| 235 | for implementing turtle graphics. |
| 236 | May be useful for turtle graphics programs also. |
| 237 | Derived from tuple, so a vector is a tuple! |
| 238 | |
| 239 | Provides (for a, b vectors, k number): |
| 240 | a+b vector addition |
| 241 | a-b vector subtraction |
| 242 | a*b inner product |
| 243 | k*a and a*k multiplication with scalar |
| 244 | |a| absolute value of a |
| 245 | a.rotate(angle) rotation |
| 246 | """ |
| 247 | def __new__(cls, x, y): |
| 248 | return tuple.__new__(cls, (x, y)) |
| 249 | def __add__(self, other): |
| 250 | return Vec2D(self[0]+other[0], self[1]+other[1]) |
| 251 | def __mul__(self, other): |
| 252 | if isinstance(other, Vec2D): |
| 253 | return self[0]*other[0]+self[1]*other[1] |
| 254 | return Vec2D(self[0]*other, self[1]*other) |
| 255 | def __rmul__(self, other): |
| 256 | if isinstance(other, int) or isinstance(other, float): |
| 257 | return Vec2D(self[0]*other, self[1]*other) |
| 258 | return NotImplemented |
| 259 | def __sub__(self, other): |
| 260 | return Vec2D(self[0]-other[0], self[1]-other[1]) |
| 261 | def __neg__(self): |
| 262 | return Vec2D(-self[0], -self[1]) |
| 263 | def __abs__(self): |
| 264 | return math.hypot(*self) |
| 265 | def rotate(self, angle): |
| 266 | """rotate self counterclockwise by angle |
| 267 | """ |
| 268 | perp = Vec2D(-self[1], self[0]) |
| 269 | angle = math.radians(angle) |
| 270 | c, s = math.cos(angle), math.sin(angle) |
| 271 | return Vec2D(self[0]*c+perp[0]*s, self[1]*c+perp[1]*s) |
| 272 | def __getnewargs__(self): |
| 273 | return (self[0], self[1]) |
| 274 | def __repr__(self): |
| 275 | return "(%.2f,%.2f)" % self |
| 276 | |
| 277 | |
| 278 | ############################################################################## |
no outgoing calls
no test coverage detected
searching dependent graphs…