Files

98 lines
2.2 KiB
Python

import math
class Vector2d:
def __init__(self, x, y):
self.points = [x, y]
@property
def x(self):
return self.points[0]
@x.setter
def x(self, value):
self.points[0] = value
@property
def y(self):
return self.points[1]
@y.setter
def y(self, value):
self.points[1] = value
def __getitem__(self, key):
return self.points[key]
def __setitem__(self, key, value):
self.points[key] = value
def __str__(self):
return "%d %d" %(self.x, self.y)
#def get_normalized_form(self):
# return Vector3d(self.x / 2, self.y / 2, self.z / 2)
class Vector3d(Vector2d):
def __init__(self, x, y, z):
self.points = [x, y, z]
def cross_product(self, vector3d):
# Returns a line that is perpendicular to the parameter
# and self.
# Returns the 'normal'.
x = self.y * vector3d.z - self.z * vector3d.y
y = self.z * vector3d.x - self.x * vector3d.z
z = self.x * vector3d.y - self.y * vector3d.x
return Vector3d(x, y, z)
def dot_product(self, vector3d):
# Returns a scalar that defines how similar two
# vectors are to one another.
return self.x * vector3d.x + self.y * vector3d.y + self.z * vector3d.z
def vector_3d_length(self):
return math.sqrt(self.dot_product(self))
def subtract_3d(self, vector3d):
return Vector3d(self.x - vector3d.x, self.y - vector3d.y, self.z - vector3d.z)
def add_3d(self, vector3d):
return Vector3d(self.x + vector3d.x, self.y + vector3d.y, self.z + vector3d.z)
def divide_3d(self, value):
return Vector3d(self.x / value, self.y / value, self.z / value)
def get_normalized_form(self):
length = self.vector_3d_length()
return Vector3d(self.x / length, self.y / length, self.z / length)
@property
def z(self):
return self.points[2]
@z.setter
def z(self, value):
self.points[2] = value
def __str__(self):
return "%d %d %d" %(self.x, self.y, self.z)
class Vector4d(Vector3d):
def __init__(self, x, y, z, w):
self.points = [x, y, z, w]
@property
def w(self):
return self.points[3]
@w.setter
def w(self, value):
self.points[3] = value
def __str__(self):
return "%d %d %d %d" %(self.x, self.y, self.z, self.w)
#def get_normalized_form(self):
# return Vector3d(self.x / 4, self.y / 4, self.z / 4)