def cull_faces(self, view_vector): """ Given a Vector representing the view, this method returns a copy of this PolygonMatrix minus all the faces that are not visible to the view. view_vector: Vector, the view vector to cull in relation to. """ if not isinstance(view_vector, Vector): raise TypeError("%s is not valid view Vector" % view_vector) culled_polygonmatrix = PolygonMatrix() for polygon in self: v1 = Vector([ polygon[2][0] - polygon[0][0], polygon[2][1] - polygon[0][1], polygon[2][2] - polygon[0][2] ]) v2 = Vector([ polygon[1][0] - polygon[0][0], polygon[1][1] - polygon[0][1], polygon[1][2] - polygon[0][2] ]) normal = Vector.cross(v1, v2) if Vector.dot(normal, view_vector) < 0: culled_polygonmatrix.add_polygon(*polygon) return culled_polygonmatrix
def tangentOnCurve(self ,param = 0.5 ,normalize = 1 ): ''' This function computes the tangent at the given parameter along the curve @type param : float @param param : At what value along the curve to sample @type normalize : bool @param normalize : whether or not to normalize the output tangent @return Vector ''' order = self.degree + 1 pos = Vector([0,0,0]) #methodA for i in range(len(cp)-1) : #First compute the basis basis = bsplineBasis(self.knots ,i+1,order-1 , param) #Then compute the Q parameter which is the derivative multiplier based on the -1 +1 control points q = Vector((degree /(self.knots[i+degree +1] - self.knots[i+1])) * (self.controlPoints[i+1] - self.controlPoints[i])) pos+= (basis*q) if normalize == 1 : return pos.normalize() else : return pos
def test_invert_vector(): """Test inverting a Vector""" vector1 = Vector([5, 5]) answer = Vector([-5, -5]) invert_vector = vector1.invert_vector() assert invert_vector == answer
def write_vector_data(data, projection, geometry, filename, keywords=None): """Write point data and any associated attributes to vector file Args: * data: List of N dictionaries each with M fields where M is the number of attributes. A value of None is acceptable. * projection: WKT projection information * geometry: List of points or polygons. * filename: Output filename * keywords: Optional dictionary Note The only format implemented is GML and SHP so the extension must be either .gml or .shp # FIXME (Ole): When the GML driver is used, # the spatial reference is not stored. # I suspect this is a bug in OGR. Background: * http://www.gdal.org/ogr/ogr_apitut.html (last example) * http://invisibleroads.com/tutorials/gdal-shapefile-points-save.html """ V = Vector(data, projection, geometry, keywords=keywords) V.write_to_file(filename)
def move(self): if self.target == Vector(self.x, self.y): print("Rat is resting.") return self.removeFromMap() if self.hunger > 0: self.lookForFood() directions = [ Vector(0, 1), Vector(0, -1), Vector(1, 0), Vector(-1, 0) ] pos = Vector(self.x, self.y) blocked = True distance = pos.distance(self.target) for direction in directions: test_pos = direction + pos if game_map.blocked(test_pos) is not True: if test_pos.distance(self.target) < distance: pos = test_pos distance = pos.distance(self.target) self.x = pos.x self.y = pos.y self.SP -= 8 self.addToMap()
def is_parallel(self, plane1): # returns if parallel or not u1 = self.normal_vector u2 = plane1.normal_vector u1_vect = Vector(u1) u2_vect = Vector(u2) return u1_vect.is_parallel_to(u2_vect)
class Printer(object): def __init__ (self, x, y, r, m, grid, move_units_per_cell): self.position = Vector(float(x), float(y)) self.r = r move_unit_pixels = grid.gridsize() / move_units_per_cell self.v = Vector(move_unit_pixels, move_unit_pixels) self.grid = grid self.penDown = False def set_position_on_grid(self, xcell, ycell): self.position = Vector((xcell * self.grid.gridsize()) + self.grid.gridsize()/2, (ycell * self.grid.gridsize())+ self.grid.gridsize()/2) def move (self): self.position = self.position.plus(self.v) def setPenUp(self): self.penDown = False def setPenDown(self): self.penDown = True def simulate(self): if self.move_is_valid(): self.move() if self.penDown: position = (self.position.x, self.position.y) self.grid.PenDraw(position) def move_is_valid(self): """ Checks if moving with the given dt will cause collision with the boundaries of the grid """ new_loc = self.position.plus(self.v) new_loc = (new_loc.x, new_loc.y) return self.grid.inbounds(new_loc)
def mutateAt(self, index): result = False blob = self.blobs[index] newBlob = blob.clone() newBlob.radius += 1 if not self.validate(newBlob): for i in range(5): offset = Vector.randomUnitCircle() * random()*i newBlob.pos += offset if self.validate(newBlob): result = True break else: result = True if not result and random() > 0.5: newBlob.radius -= 1 for i in range(5): offset = Vector.randomUnitCircle() * random()*i if self.validate(newBlob): result = True if result: self.blobs[index] = newBlob return result
class Particle: def __init__(self, color, pos, vel=None, mass=1): self.color = color self.pos = pos self.prev = pos self.vel = (Vector(0,0) if vel is None else vel) self.force = Vector(0,0) self.mass = mass self.radius def __str__(self): return "P("+str(self.pos.x)+", "+str(self.pos.y)+")" def applyForce(self, force): self.force = self.force.add(force) def update(self, time): self.prev = self.pos.copy() accel = self.force.mul(1/self.mass) self.force = Vector(0,0) self.vel = self.vel.add(accel.mul(time)) self.pos = self.pos.add(self.vel.mul(time))
def load_myformat(self, filename): filetext=file(filename, 'r') go_lines=filetext.readlines() header=go_lines[0:6] self.title=header[1] self.game_commentary=header[3] self.setsize(header[5]) movelines=go_lines[7:] # go_lines=str.splitlines(filetext) # go_lines=filetext.splitlines() # # TODO add the part to read the header and board size # for line in movelines: content=line.split(None,2) number=content[0] color=content[1] pos=Vector() # pos.fromString3(content[2].strip(" ")) pos.fromString(content[2].strip(" ")) next_move=stone.Stone(number,color,pos) self.moves.append(next_move)
def apply(boids, bj): pcj = Vector() for b in boids: if b != bj: pcj.sum(b.position) pcj = pcj.div(len(boids) - 1) return pcj.minus(bj.position).div(100)
def __init__(self, x=50, y=50): self.pos = Vector(x, y); self.speed = Vector(); self.accel = Vector(); self.angle = 0; self.tmpAngle = 0; self.canShoot = 1; self.shootLimiter = Timer(2); self.keyb = 1; self.keys = { "up":0, "down":0, "left":0, "right":0, "shoot":0 }; self.mouse = Vector(0,0); self.mShoot = 0; self.accel.x = 1; self.points = ( Vector(0,-10), Vector(0,10), Vector(30,0) );
def computeScores(inputDir, outCSV, acceptTypes): with open(outCSV, "wb") as outF: a = csv.writer(outF, delimiter=',') a.writerow(["x-coordinate","y-coordinate","Similarity_score"]) files_tuple = itertools.combinations(filterFiles(inputDir, acceptTypes), 2) for file1, file2 in files_tuple: try: row_cosine_distance = [file1, file2] file1_parsedData = parser.from_file(file1) file2_parsedData = parser.from_file(file2) v1 = Vector(file1, ast.literal_eval(file1_parsedData["content"])) v2 = Vector(file2, ast.literal_eval(file2_parsedData["content"])) row_cosine_distance.append(v1.cosTheta(v2)) a.writerow(row_cosine_distance) except ConnectionError: sleep(1) except KeyError: continue except Exception, e: pass
def make_matrix(vector_list): ''' Make a matrix out of a list of vectors 'vector_list' Just like make_vector in the vector module, this decides whether to instantiate the FullMatrix or SparseMatrix class by using the is_zero method of the Vector class ''' count = 0 for vector1 in vector_list: vector_obj = Vector(vector1, zero_test = lambda x : (x == 0)) if(vector_obj.is_zero()==True): count = count+1 if((count/len(vector_list))>DENSITY_THRESHOLD and len(vector_list)>SIZE_THRESHOLD): i = 0 matrix_elmts = [] matrix_indices = [] while(i<len(vector_list)): vector_obj1 = Vector(vector_list[i] , zero_test = lambda x : (x == 0)) if(vector_obj1.is_zero()==True): matrix_elmts.append(vector_list[i]) matrix_indices.append(i) i = i+1 else: i = 0 matrix_elmts = [] while(i<len(vector_list)): matrix_elmts.append(vector_list[i]) i = i+1
def __init__(self, minimum, maximum, target_minimum=None, target_maximum=None, ratio=None): self.minimum = minimum self.maximum = maximum if not target_minimum: target_minimum = Vector() if not target_maximum: target_maximum = maximum - minimum space = Vector() if ratio: if ratio == 'geo': ratio = math.sin((90.0 - ((self.maximum.y + self.minimum.y) / 2.0)) / 180.0 * math.pi) current_ratio = (self.maximum.x - self.minimum.x) * ratio / (self.maximum.y - self.minimum.y) target_ratio = (target_maximum.x - target_minimum.x) / (target_maximum.y - target_minimum.y) if current_ratio >= target_ratio: n = (target_maximum.x - target_minimum.x) / (maximum.x - minimum.x) / ratio space.y = ((target_maximum.y - target_minimum.y) - (maximum.y - minimum.y) * n) / 2.0 space.x = 0 else: n = (target_maximum.y - target_minimum.y) / (maximum.y - minimum.y) space.x = ((target_maximum.x - target_minimum.x) - (maximum.x - minimum.x) * n) / 2.0 space.y = 0 target_minimum.x += space target_maximum.x += space self.target_minimum = target_minimum self.target_maximum = target_maximum
def test_copy(): vec = Vector(1, 2, 3) vec_copy = vec.copy() vec_copy += 100 assert vec != vec_copy
def scan(self, bot): # menor distancia ate agora menor = VISAO ind = -1 # itera todos bots for b in self.bots: # se nao eh o proprio e esta ativo if b is not bot and b.ativo: # calcula distancia entre os bots distancia = (bot.posicao - b.posicao).length() # verifica se a distancia esta dentro do limiar aceitavel # e eh menor que a menor encontrada ate agora if distancia-RAIO <= VISAO and distancia < menor: vet_canhao = Vector(cos(bot.direcao + bot.canhao), sin(bot.direcao + bot.canhao)) vet_alvo = b.posicao - bot.posicao angulo = vet_canhao.angle(vet_alvo) if angulo <= mod(bot.arco/2.0 + atan2(RAIO, (bot.posicao - b.posicao).length()), PI): ind = b.indice menor = distancia return menor, ind
def __init__(self, minimum, maximum, target_minimum=None, target_maximum=None): self.minimum = minimum self.maximum = maximum # Ratio is depended of latitude. It is always <= 1. # In one latitude degree is always 40 000 / 360 km. # In one current longitude degree is about 40 000 / 360 * ratio km. ratio = math.sin((90.0 - ((self.maximum.lat + self.minimum.lat) / 2.0)) / 180.0 * math.pi) # Longitude displayed as x. # Latitude displayed as y. # Ratio is x / y. space = Vector() current_ratio = (self.maximum.lon - self.minimum.lon) * ratio / (self.maximum.lat - self.minimum.lat) target_ratio = (target_maximum.x - target_minimum.x) / (target_maximum.y - target_minimum.y) if current_ratio >= target_ratio: n = (target_maximum.x - target_minimum.x) / (maximum.lon - minimum.lon) / ratio space.y = ((target_maximum.y - target_minimum.y) - (maximum.lat - minimum.lat) * n) / 2.0 space.x = 0 else: n = (target_maximum.y - target_minimum.y) / (maximum.lat - minimum.lat) * ratio space.x = ((target_maximum.x - target_minimum.x) - (maximum.lon - minimum.lon) * n) / 2.0 space.y = 0 self.target_minimum = target_minimum + space self.target_maximum = target_maximum - space self.space = space
def test_cclockise(self): start = Vertex(2,1) base_vector = Vector(start, Vertex(3,1)) cclockwise = ((1,0),(2,0),(3,0)) not_cclockwise = ((1,1),(3,2),(2,2),(1,2),(3,1)) self.assertListEqual([base_vector.is_cclockwise(Vector(start, Vertex(v[0],v[1]))) for v in cclockwise], [True for x in range(len(cclockwise))]) self.assertListEqual([base_vector.is_cclockwise(Vector(start, Vertex(v[0],v[1]))) for v in not_cclockwise], [False for x in range(len(not_cclockwise))])
def draw_arrow(canvas, point_from, point_to, color=Color(), width=1.0): """ @type canvas: drawing.canvas.Canvas @type point_from: vector.Vector @type point_to: vector.Vector @type color: Color @type width: float """ point_from = Vector.vectorize(point_from) point_to = Vector.vectorize(point_to) DrawingUtils.draw_line(canvas, point_from, point_to, color, width) vec_arrow = point_to.sub(point_from) wing = vec_arrow.inverse().normalized().scaled(10) wing_right = wing.rotate(45) wing_left = wing.rotate(-45) DrawingUtils.draw_line(canvas, point_to, wing_right.add(point_to), color, width) DrawingUtils.draw_line(canvas, point_to, wing_left.add(point_to), color, width)
class Car(object): def __init__(self, position): self.position = position self.velocity = Vector(0, 0) self.alive = True def update(self, dt, height, acceleration, tangent): drag = -self.velocity.normalized() if self.velocity.length() > 0 else \ Vector(0, 0) if height > 0: acc = tangent * acceleration + tangent * GRAVITY.dot(tangent) \ - drag else: acc = GRAVITY - drag velocity_old = self.velocity self.velocity = self.velocity + acc * dt # Check death. impulse = (velocity_old - self.velocity).length() print "impulse:", impulse if impulse > 150: print "DIE!" self.alive = False self.position = self.position + self.velocity * dt
def testNormalizedHandlesZeroVectorWithException(self): v1 = Vector([0,0]) with self.assertRaises(Exception) as context: v1.normalized() self.assertTrue('Cannot normalize the zero vector' in str(context.exception))
def test_eq(self): v5 = Vector(0,0) v5.x = 5 v5.y = 5 #self.assertEqual(v5,self.vec5) self.assertTrue(v5 == self.vec5) self.assertTrue((v5 == self.vec1) is False)
def test_left_orthogonal(self): start, end = Vertex(0,0), Vertex(2,1) vector = Vector(start, end) ort_vector = vector.left_orthogonal() self.assertListEqual([ort_vector.x, ort_vector.y], [ -1, 2]) self.assertListEqual([ort_vector.start, ort_vector.end], [ start, Vertex(-1, 2)])
class Entity(pygame.sprite.Sprite): def __init__(self, bounds=[0,600,0,800], size=(4,4)): pygame.sprite.Sprite.__init__(self) self.__update_surface_size(size) #creates scope variable "image", which is a pygame surface self.alive = True self.bounds = bounds self.vector = Vector() def die(self): self.alive = False self.vector.dx = 0 self.vector.dy = 0 def update(self, timestep = 1): self.update_position(timestep) def __update_position(self, timestep = 1): self.vector.update(timestep) def __update_surface_size(self, size=(1,1)): self.image = pygame.Surface(size) def set_size(self, size=(1,1)): self.update_surface_size(size) @property def orientation(self): return self.vector.orientation() @property def rect(self): return self.image.get_rect(topleft=(self.vector.x,self.vector.y))
def reflex_factor(self, eartip): A, B, C = self.tri_at(eartip) AB = B - A BC = C - B # vector pointing outside AB_out = Vector.cross(AB, self.normal).unit() return Vector.dot(AB_out, BC.unit())
def calculateLocation(self, robot_classification, bucket): ''' If the location can be taken from the bucket, return the mean ''' if bucket is not None and len(bucket) > 1: points = [x for (x, _) in bucket] return meanPoint(points) if not self.previous_locations[robot_classification].full(): return None ''' Get the ArrayQueue(previous locations) for robot with the 'key' identifier ''' points_queue = self.previous_locations[robot_classification] trajectory_vector = linear_regression(points_queue) if trajectory_vector is None: return None trajectory_vector.rescale(1) speed = self.getSpeed(robot_classification) dislocation = Vector.scalarMultiple(trajectory_vector, speed) prev_location = points_queue.getLeft() estimated_robot_position = Vector.addToPoint( prev_location, dislocation ) if self.outOfBounds(estimated_robot_position): return None return estimated_robot_position
def __init__(self,n,x,y): brain = Perceptron(n,0.001) self.location = Vector([x,y]) self.velocity = Vector([0,0]) self.acceleration = Vector([0,0]) self.maxforce = 0.1 self.maxspeed = 4
def test_ne(self): v5 = Vector(0,0) v5.x = 5 v5.y = 5 self.assertEqual(v5,self.vec5) self.assertTrue(v5 != self.vec1) self.assertTrue((v5 != self.vec5) is False)
def fromelement(cls, maptree, terrainmap=None, tokenmap=None): # get the size esize = maptree.find("size") if esize is None: raise MapError("A map must have a size") else: evec = esize[0] size = Vector.fromelement(evec) # and the origin eorigin = maptree.find("origin") if eorigin is not None: evec = eorigin[0] origin = Vector.fromelement(evec) else: origin = Vector.ORIGIN # and the name, game and copyright hm = cls(size, origin) # add the terrains for eterrain in maptree.findall("terrain"): tname = eterrain.get("type") if tname in terrainmap: terrain = terrainmap[tname].fromelement(eterrain, hm) hm.addTerrain(terrain) else: print "terrain name %s not in terrain map %s" % (tname, terrainmap) return hm
def test_sub(self): vector1 = Vector(5, 6) vector2 = Vector(2, 2) sub = vector1 - vector2 self.assertEqual(sub, Vector(3, 4))
from vector import Vector #VALID TESTS integer = 4 float_list = [1.0, 2.0, 3.0] int_range = (10, 13) try: v1 = Vector(integer) v2 = Vector(float_list) v3 = Vector(int_range) print(str(v1), end = '') print(str(v2), end = '') print(str(v3), end = '') except: pass #INVALID TESTS integer = "3" float_list = [0.0, 1.0, "2.0"] int_range = ("10", 15) try: fv1 = Vector(integer) fv2 = Vector(float_list) fv3 = Vector(int_range) int_range = (10, 15, 20) fv4 = Vector(int_range) except: pass #VALID OPERATIONS v4 = v2 + v3
import sys from vector import Vector vec = Vector([0, 1, 2]) # vec = Vector(4) # vec = Vector((2, 7)) # vec = Vector(['a']) # vec = Vector('a') # vec = Vector(0) # vec = Vector(-1) # vec = Vector((0, 0)) # vec = Vector((0)) # vec = Vector((5, 2, 6)) # vec = Vector([]) # vec = Vector(()) vec2 = Vector([0, 2, 4]) vec4 = Vector([0, 2]) vec3 = vec + vec2 # vec3 = vec + 1 # vec3 = vec + vec4 # vec3 = vec + 'd' # vec3 = 1 + vec # vec3 = 'd' + vec # vec3 = vec - vec2 # vec3 = vec - 1 # vec3 = vec - vec4 # vec3 = vec - 'd' # vec3 = 1 - vec # vec3 = 'd' - vec # vec3 = vec - {'a': 1}
from vector import Vector liste = [0.0, 1.0, 2.0, 3.0] range_tuple = (10, 17) toto = Vector(liste) # print(toto.size) # print(toto.values) vec1 = Vector((15, 20)) print("vec1 values", vec1.values) vec2 = 2 * vec1 # print("vec1 values after op", vec1.values) print("vec2 values", vec2.values)
def test_mul_scalar(self): vector1 = Vector(13, 65, 4.5) vector2 = Vector(2, 22.3, 3) mul = vector1 * vector2 self.assertEqual(mul, 1489)
def test_add(self): vector1 = Vector(10, 5) vector2 = Vector(3, 20) sum = vector1 + vector2 self.assertEqual(sum, Vector(13, 25))
def test_string_representation(self): vector = Vector(3, 53, False) self.assertEqual(str(vector), "Vector3(3, 53, False)")
def test_clear(self): vector = Vector(3, 53, False, None, "Hello") vector.clear() self.assertEqual(len(vector), 0)
def test_len(self): vector = Vector(3, 53, False, None, "Hello") self.assertEqual(len(vector), 5)
def test_mul_by_const(self): vector = Vector(10, 20, "AB") mul = vector * 2 self.assertEqual(mul, Vector(20, 40, "ABAB"))
def collide_player(self, box_collider: Box, potential_position): # potential_position = self.position + self.velocity collided = False if type(box_collider) is Player: is_player = True else: is_player = False nearest_point = Vector(0, 0) nearest_point.x = max( box_collider.position.x - box_collider.half_size.x, min(potential_position.x, box_collider.position.x + box_collider.half_size.x)) nearest_point.y = max( box_collider.position.y - box_collider.half_size.y, min(potential_position.y, box_collider.position.y + box_collider.half_size.y)) ray_to_nearest = nearest_point - potential_position overlap = self.radius - ray_to_nearest.mag() if ray_to_nearest.mag() == 0: overlap = 0 if overlap > 0: potential_position = potential_position - ( ray_to_nearest.normalized() * overlap) right = (Vector(1, 0)).cos_angle(potential_position - box_collider.position) right_rec = (Vector(1, 0)).cos_angle( Vector(box_collider.half_size.x, -box_collider.half_size.y)) left_rec = (Vector(1, 0)).cos_angle( Vector(-box_collider.half_size.x, -box_collider.half_size.y)) collided_top = left_rec <= right <= right_rec top = (Vector(0, 1)).cos_angle(potential_position - box_collider.position) down_rec = (Vector(0, 1)).cos_angle( Vector(-box_collider.half_size.x, box_collider.half_size.y)) top_rec = (Vector(0, 1)).cos_angle( Vector(-box_collider.half_size.x, -box_collider.half_size.y)) collided_right = top_rec <= top <= down_rec if collided_top: if not is_player: self.velocity = Vector(self.velocity.x, -self.velocity.y) else: self.velocity = (potential_position - box_collider.position ).normalized() * self.current_speed if collided_right: self.velocity = Vector(-self.velocity.x, self.velocity.y) if not is_player: self.score.add_score() self.current_speed += 10 self.velocity = self.velocity.normalized() * self.current_speed collided = True return potential_position, collided
def __init__(self, image): self.image = image self.offset = Vector(random.randint(-20, 20), random.randint(-20, 20)) self.countdown = 100
from image import Image from pixel import Pixel from scene import Scene from sphere import Sphere from vector import Vector from camera import Camera from point import Point from material import Material, ChequeredMaterial from light import Light COLS = 1920 ROWS = 1080 RENDEREDIMG = "twospheres.ppm" CAMERA = Camera(Vector(0, -0.35, -1)) OBJECTS = [ #Ground Sphere( Point(0, 10000.5, 1), 10000.0, ChequeredMaterial(color1=Pixel.fromHex("#420500"), color2=Pixel.fromHex("#E6B87D"), ambient=0.2, reflection=0.2)), #Blue ball Sphere(Point(0.75, -.1, 1), 0.6, Material(Pixel.fromHex("#0000FF"))), #Pink ball Sphere(Point(-0.75, -0.1, 2.25), 0.6, Material(Pixel.fromHex("#803980"))) ] LIGHTS = [ Light(Point(1.5, -.5, -10), Pixel.fromHex("#FFFFFF")), Light(Point(-.5, -10, -10), Pixel.fromHex("#E6E6E6")) ]
class Ball: def __init__(self, window: GraphWin, initial_position: Vector, radius: float, speed: float, initial_direction: Vector, score: Score, lose_life_function): self.window = window self.initial_direction = initial_direction self.initial_position = initial_position self.radius = radius self.initial_speed = speed self.current_speed = speed self.score = score self.is_alive = True self.still_ball = True self.position = self.initial_position self.velocity = self.initial_direction * speed self.sprite = Circle(self.position.to_point(), self.radius) self.damage = lose_life_function def draw(self, window: GraphWin): self.sprite.undraw() self.sprite = Circle(self.position.to_point(), self.radius) self.sprite.setFill("green") self.sprite.draw(window) def undraw(self): self.sprite.undraw() def reset(self): self.move_ball(self.initial_position) self.velocity = self.initial_direction * self.initial_speed self.is_alive = True self.still_ball = True self.current_speed = self.initial_speed def release(self): self.still_ball = False def update(self, elapsed_time: float, player: Player, squares: Sequence[PointSquare]): if self.still_ball: self.move_ball(player.position + Vector(0, -(self.radius + 10))) return self.world_collide() potential_position = self.position + (self.velocity * elapsed_time) new_potential_position, collided = self.collide_player( player, potential_position) if collided: potential_position = new_potential_position else: for square in squares: if not square.is_active: continue new_potential_position, collided = self.collide_player( square, potential_position) if collided: square.hit() potential_position = new_potential_position break self.move_ball(potential_position) def move_ball(self, new_position: Vector): delta = new_position - self.position self.sprite.move(delta.x, delta.y) self.position = new_position def world_collide(self): if self.position.x - self.radius <= 0 or self.position.x + self.radius >= self.window.width: self.velocity = Vector(-self.velocity.x, self.velocity.y) if self.position.x > self.window.width / 2: self.move_ball( Vector(self.window.width - (self.radius + 5), self.position.y)) else: self.move_ball(Vector(0 + (self.radius + 5), self.position.y)) if self.position.y - self.radius <= 0 or self.position.y + self.radius >= self.window.height: self.velocity = Vector(self.velocity.x, -self.velocity.y) if self.position.y > self.window.height / 2: self.damage() else: self.move_ball(Vector(self.position.x, 0 + self.radius + 5)) def collide_player(self, box_collider: Box, potential_position): # potential_position = self.position + self.velocity collided = False if type(box_collider) is Player: is_player = True else: is_player = False nearest_point = Vector(0, 0) nearest_point.x = max( box_collider.position.x - box_collider.half_size.x, min(potential_position.x, box_collider.position.x + box_collider.half_size.x)) nearest_point.y = max( box_collider.position.y - box_collider.half_size.y, min(potential_position.y, box_collider.position.y + box_collider.half_size.y)) ray_to_nearest = nearest_point - potential_position overlap = self.radius - ray_to_nearest.mag() if ray_to_nearest.mag() == 0: overlap = 0 if overlap > 0: potential_position = potential_position - ( ray_to_nearest.normalized() * overlap) right = (Vector(1, 0)).cos_angle(potential_position - box_collider.position) right_rec = (Vector(1, 0)).cos_angle( Vector(box_collider.half_size.x, -box_collider.half_size.y)) left_rec = (Vector(1, 0)).cos_angle( Vector(-box_collider.half_size.x, -box_collider.half_size.y)) collided_top = left_rec <= right <= right_rec top = (Vector(0, 1)).cos_angle(potential_position - box_collider.position) down_rec = (Vector(0, 1)).cos_angle( Vector(-box_collider.half_size.x, box_collider.half_size.y)) top_rec = (Vector(0, 1)).cos_angle( Vector(-box_collider.half_size.x, -box_collider.half_size.y)) collided_right = top_rec <= top <= down_rec if collided_top: if not is_player: self.velocity = Vector(self.velocity.x, -self.velocity.y) else: self.velocity = (potential_position - box_collider.position ).normalized() * self.current_speed if collided_right: self.velocity = Vector(-self.velocity.x, self.velocity.y) if not is_player: self.score.add_score() self.current_speed += 10 self.velocity = self.velocity.normalized() * self.current_speed collided = True return potential_position, collided
def __init__(self, x: float, y: float, width: float, height: float)\ -> None: self.origin: Vector = Vector(x, y) self.size: Vector = Vector(width, height)
self.basepoint = Vector(basepoint_coords) except NoNonZeroElementsLineException: self.basepoint = None def intersection_with(self, line): try: A, B = self.normal_vector.coordinates C, D = line.normal_vector.coordinates k1 = self.constant_term k2 = line.constant_term x_numerator = D*k1 - B*k2 y_numerator = C*k1 + A*k2 one_over_denom = Decimal('1')/(A*D - B*C) return (Vector([x_numerator, y_numerator]) .times_scalar(one_over_denom)) except ZeroDivisionError: return self if self == line else None class MyDecimal(Decimal): def is_near_zero(self, eps=1e-10): return abs(self) < eps if __name__ == '__main__': line1 = Line(normal_vector=Vector(['4.046', '2.836']), constant_term='1.21') line2 = Line(normal_vector=Vector(['10.115', '7.09']), constant_term='3.025') print(f'intersection 1: {line1.intersection_with(line2)}')
def points(self) -> Iterator[Vector]: yield self.origin yield self.origin + Vector(self.size.width, 0) yield self.origin + Vector(0, self.size.height) yield self.origin + self.size
def print_banner(srg): print() print(srg.ljust(20 + len(srg), '|').rjust(40 + len(srg), '|')) print() def print_oper(a0, op, a1, a2): lenj = max(len(str(a0)), len(str(a1)), len(str(a2))) + 3 print(str(a0).rjust(lenj, ' ')) print(op) print(str(a1).rjust(lenj, ' ')) print(''.rjust(lenj, '-')) print(str(' = ' + str(a2)).rjust(lenj, ' ')) vec = Vector((10, 16)) print('vec = Vector((10, 16)): ' + str(vec)) vec = Vector(0) print('vec = Vector(0): ' + str(vec)) vec = Vector([2.0, 3.0, 8, 7.0]) print('vec = Vector([2.0, 3.0, 8.0, 7.0]): ' + str(vec)) vec = Vector([1, 2, 3, 4]) print_banner(' vec + vec = vec ') vec0 = Vector((5, 10)) vec1 = Vector((6, 11)) vec2 = vec0 + vec1 print_oper(vec0.values, ' + ', vec1.values, vec2.values) print_banner(' vec + sca = vec ') vec0 = Vector((5, 10)) sca = 5 vec1 = vec0 + sca
class Plane(object): NO_NONZERO_ELTS_FOUND_MSG = 'No nonzero elements found' def __init__(self, normal_vector=None, constant_term=None): self.dimension = 3 if not normal_vector: all_zeros = ['0'] * self.dimension normal_vector = Vector(all_zeros) self.normal_vector = normal_vector if not constant_term: constant_term = Decimal('0') self.constant_term = Decimal(constant_term) self.set_basepoint() def set_basepoint(self): try: n = self.normal_vector c = self.constant_term basepoint_coords = ['0'] * self.dimension initial_index = Plane.first_nonzero_index(n) initial_coefficient = n[initial_index] basepoint_coords[initial_index] = c / initial_coefficient self.basepoint = Vector(basepoint_coords) except Exception as e: if str(e) == Plane.NO_NONZERO_ELTS_FOUND_MSG: self.basepoint = None else: raise e def __str__(self): num_decimal_places = 3 def write_coefficient(coefficient, is_initial_term=False): coefficient = round(coefficient, num_decimal_places) if coefficient % 1 == 0: coefficient = int(coefficient) output = '' if coefficient < 0: output += '-' if coefficient > 0 and not is_initial_term: output += '+' if not is_initial_term: output += ' ' if abs(coefficient) != 1: output += '{}'.format(abs(coefficient)) return output n = self.normal_vector try: initial_index = Plane.first_nonzero_index(n) terms = [ write_coefficient(n[i], is_initial_term=(i == initial_index)) + 'x_{}'.format(i + 1) for i in range(self.dimension) if round(n[i], num_decimal_places) != 0 ] output = ' '.join(terms) except Exception as e: if str(e) == self.NO_NONZERO_ELTS_FOUND_MSG: output = '0' else: raise e constant = round(self.constant_term, num_decimal_places) if constant % 1 == 0: constant = int(constant) output += ' = {}'.format(constant) return output def is_parallel(self, plane2): return self.normal_vector.is_parallel(plane2.normal_vector) def __eq__(self, plane2): if self.normal_vector.is_zero(): if not plane2.normal_vector.is_zero(): return 0 diff = self.constant_term - plane2.constant_term return MyDecimal(diff).is_near_zero() elif plane2.normal_vector.is_zero(): return 0 if not self.is_parallel(plane2): return 0 basepoint_difference = self.basepoint.minus(plane2.basepoint) return basepoint_difference.is_orthogonal(self.normal_vector) def __iter__(self): self.current = 0 return self def next(self): if self.current >= len(self.normal_vector): raise StopIteration else: current_value = self.normal_vector[self.current] self.current += 1 return current_value def __len__(self): return len(self.normal_vector) def __getitem__(self, i): return self.normal_vector[i] @staticmethod def first_nonzero_index(iterable): for k, item in enumerate(iterable): if not MyDecimal(item).is_near_zero(): return k raise Exception(Plane.NO_NONZERO_ELTS_FOUND_MSG)
from vector import Vector v = Vector(3) v2 = Vector([0.0, 1.0, 2.0, 3.0]) v3 = Vector((10, 15)) v4 = v3 + 2 v6 = 2 + v2 v7 = v6 - 5 print('==========================') v8 = 9 - v v8 = v - 9 print('==========================') v10 = 3 * v3 v11 = v3 * 3 print(v) print(v4) print(v6)
from sphere import Sphere from triangle import Triangle from plane import Plane import math from camera import Camera HEIGHT = 400 WIDTH = 400 objectlist = [] BACKGROUND_COLOR = (255,255,255) img = Image.new('RGB',(WIDTH,HEIGHT)) if __name__ == "__main__": sphere1 = Sphere(Vector(2.5,3,-10), 2, (255,0,0)) sphere2 = Sphere(Vector(0, 7, -10), 2, (0, 0, 255)) sphere3 = Sphere(Vector(-2.5, 3, -10), 2, (0, 255, 0)) plane = Plane(Point(-20,-20,-100),Vector(0,1,0),(55,55,0)) trangle = Triangle(Point(-2.5,3,-11),Point(0,7,-11),Point(2.5,3,-11),(0,0,255)) img = Image.new('RGB', (WIDTH, HEIGHT)) camera = Camera([sphere1,sphere2,sphere3,trangle,plane],img,WIDTH, HEIGHT, 45.0) ray = Ray(Vector(0,0,-10), Vector(0,0.05,1)) print(sphere1.intersectionParameter(ray)) img = camera.run() img.save("test.png")
def target(self, pos): if self.currentlyTargeting and self.dazeCount == 0: self.vel = Vector(pos.get_p()[0] - self.pos.get_p()[0], pos.get_p()[1] - self.pos.get_p()[1]).normalize() else: self.daze_cycle()
def row(self, index: int) -> Vector: """Returns the row in a given index""" return Vector(self.elements[index])
def wall_is_present(self, dir_vector): selected_pos = self.grid_pos.multiply_vectors(Vector( 1, -1)).add_vector(dir_vector) print(self.maze[selected_pos.y, selected_pos.x] == self.WALL) return self.maze[selected_pos.y, selected_pos.x] == self.WALL
class MazeManager(object): def __init__(self): ''' the maze variable is a two dimensional numpy array containing integer values which specify the type of tile at the position 0 --> an unvisited tile 1 --> a visited tile 2 --> a wall/corner 3 --> a passage 4 --> the end tile 5 --> an undefined tile ''' # The strings to be printed for each grid tile self.UNVISITED = ANSIColorPrinter.add_color(" ", "teal", highlight=True) self.VISITED = "::" self.WALL = ANSIColorPrinter.add_color(" ", "red", highlight=True) self.PASSAGE = " " self.END = ANSIColorPrinter.add_color(" ", "green", highlight=True) self.UNDEFINED = ANSIColorPrinter.add_color(" ", "white", highlight=True) self.ROBOT = ANSIColorPrinter.add_color(" ", "green", highlight=True) # This section contains user defined variables self.wall_probability = 0.4 # This section class variables and operations which are used to initialize the object self.maze = array([ [self.UNDEFINED, self.UNDEFINED, self.UNDEFINED], [self.UNDEFINED, self.VISITED, self.UNDEFINED], [self.UNDEFINED, self.UNDEFINED, self.UNDEFINED], ]) self.maze_height = 3 self.maze_width = 3 self.offset = Vector(1, 1) self.position = Vector(0, 0) self.grid_pos = Vector(3, 3) self.dir_vectors = [ Vector(0, 1), Vector(1, 0), Vector(0, -1), Vector(-1, 0) ] for dir_vector in self.dir_vectors: self.expand_maze(dir_vector) self.generate_surroundings() # Converts a maze coordinate into a grid coordinate def get_grid_coord(self, pos_vector): return_vector = pos_vector.multiply_vectors(Vector(2, -2)).add_vector( self.offset) return return_vector # Scans for an existing wall and returns True if found, False otherwise def wall_is_present(self, dir_vector): selected_pos = self.grid_pos.multiply_vectors(Vector( 1, -1)).add_vector(dir_vector) print(self.maze[selected_pos.y, selected_pos.x] == self.WALL) return self.maze[selected_pos.y, selected_pos.x] == self.WALL # Moves the robot in the direction of the direction vector def move_robot(self, dir_vector): self.position = self.position.add_vector(dir_vector) self.grid_pos = self.get_grid_coord(self.position) # Checks if it is necessary to expand the maze, and does so if necessary if (self.grid_pos.y > self.maze_height - 3 or self.grid_pos.y < 3 or self.grid_pos.x > self.maze_width - 3 or self.grid_pos.x < 3): self.expand_maze(dir_vector) self.grid_pos = self.get_grid_coord(self.position) self.maze[self.grid_pos.y, self.grid_pos.x] = self.VISITED self.generate_surroundings() # Generates the surrounding walls/passages. Must have had move_robot(...) called prior. def generate_surroundings(self): for dir_vector in self.dir_vectors: selected_pos = self.grid_pos.add_vector(dir_vector) if self.maze[selected_pos.y, selected_pos.x] == self.UNDEFINED: if randint( 0, 100 ) < self.wall_probability * 100: # If the generator chooses wall self.maze[selected_pos.y, selected_pos.x] = self.WALL else: self.maze[selected_pos.y, selected_pos.x] = self.PASSAGE selected_pos = selected_pos.add_vector(dir_vector) self.maze[selected_pos.y, selected_pos.x] = self.UNVISITED # Expands the maze in the direction of dir_vector def expand_maze(self, dir_vector): if dir_vector.x == 0: self.maze_height += 2 if dir_vector.y > 0: # North self.maze = concatenate( (full([2, self.maze_width], self.UNDEFINED), self.maze), axis=0) self.offset = self.offset.add_vector(Vector(0, 2)) else: # South self.maze = concatenate( (self.maze, full([2, self.maze_width], self.UNDEFINED)), axis=0) else: self.maze_width += 2 if dir_vector.x > 0: # East self.maze = concatenate( (self.maze, full([self.maze_height, 2], self.UNDEFINED)), axis=1) else: # West self.offset = self.offset.add_vector(Vector(2, 0)) self.maze = concatenate( (full([self.maze_height, 2], self.UNDEFINED), self.maze), axis=1) def print_maze(self): for row_index in range(0, len(self.maze)): for col_index in range(0, len(self.maze[row_index])): if self.grid_pos.x == col_index and self.grid_pos.y == row_index: print(self.ROBOT, end="") else: print(self.maze[row_index][col_index], end="") print()
def col(self, index: int) -> Vector: """Returns the column in a given index""" return Vector([row[index] for row in self.elements])
def test_index_out_of_bounds(self): vector = Vector(43, 12, 56) with self.assertRaises(Exception): vector[4]
raise Exception(self.ALL_PLANES_MUST_BE_IN_SAME_DIM_MSG) def __str__(self): ret = 'Linear System:\n' temp = ['Equation {}: {}'.format(i+1,p) for i,p in enumerate(self.planes)] ret += '\n'.join(temp) return ret class MyDecimal(Decimal): def is_near_zero(self, eps=1e-10): return abs(self) < eps p1 = Plane(normal_vector=Vector([5.862, 1.178, -10.366]), constant_term=-8.15) p2 = Plane(normal_vector=Vector([-2.931, -0.589, 5.183]), constant_term=-4.075) s = LinearSystem([p1, p2]) t = s.compute_rref() print(s) print('solution {}'.format(t)) print() p1 = Plane(normal_vector=Vector([8.631, 5.112, -1.816]), constant_term=-5.113) p2 = Plane(normal_vector=Vector([4.315, 11.132, -5.27]), constant_term=-6.775) p3 = Plane(normal_vector=Vector([-2.158, 3.01, -1.727]), constant_term=-0.831) s = LinearSystem([p1, p2, p3]) t = s.compute_rref() print(s) print('solution {}'.format(t)) print()
def test_get_by_index(self): vector = Vector(43, 12, 56) self.assertEqual(vector[1], 12)
def get_grid_coord(self, pos_vector): return_vector = pos_vector.multiply_vectors(Vector(2, -2)).add_vector( self.offset) return return_vector