MCPcopy Create free account
hub / github.com/codemistic/Data-Structures-and-Algorithms / Vec2D

Class Vec2D

Python/Turtle.py:134–176  ·  view source on GitHub ↗

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

Source from the content-addressed store, hash-verified

132
133
134class 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##############################################################################

Callers 14

__add__Method · 0.85
__mul__Method · 0.85
__rmul__Method · 0.85
__sub__Method · 0.85
__neg__Method · 0.85
rotateMethod · 0.85
TNavigatorClass · 0.85
resetMethod · 0.85
gotoMethod · 0.85
setxMethod · 0.85
setyMethod · 0.85
distanceMethod · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected