class Player(GameObject): def __init__(self, x, y): super(Player, self).__init__(x*40, y*40, 40, 40) self.velocity = Vector() self.terminal_velocity = 5.0 self.airborne = False def update(self, delta): self.velocity += gravity * delta if self.velocity.y > self.terminal_velocity: self.velocity.y = self.terminal_velocity self.velocity.add_to_rect(self.rect) self.airborne = True sprites = pygame.sprite.spritecollide(self, self.level.platforms, dokill=False) if sprites: self.rect.y = sprites[0].rect.y - 40 self.airborne = False def is_updatable(self): return True def setup(self, level): self.level = level self.level.player = self def left_down(self): self.velocity += left def left_up(self): self.velocity += right def right_down(self): self.velocity += right def right_up(self): self.velocity += left def jump_start(self): if not self.airborne: self.airborne = True self.velocity += up def jump_end(self): pass
def __post_init__(self): super().__post_init__() self._set_fields_from_subproperty_data( ("name", 0x494E414D, unpack_null_terminated_ascii), ("translation", 0x5846524D, lambda data: Vector.from_packed(data[:12])), ("rotation", 0x5846524D, lambda data: Vector.from_packed(data[12:24])), ("scale", 0x5846524D, lambda data: Vector.from_packed(data[24:])), ("active", 0x41435456, unpack_bool), )
class HexBlock: Xs = Vector([-1.0, -0.5, 0.5, 1, 0.5, -0.5]) Ys = Vector([.0, halfSq3, halfSq3, .0, -halfSq3, -halfSq3]) Vec = [Vector(v) for v in [(0, 1), (halfSq3, 0.5), (halfSq3, -0.5)]] def __init__(self, win, edgeLen, center): self.win = win self.X, self.Y = center self.xs = HexBlock.Xs * edgeLen self.ys = HexBlock.Ys * edgeLen self.edgeLen = edgeLen self.player = None points = [] for i in range(6): points.append(Point(self.xs[i] + self.X, self.ys[i] + self.Y)) self.region = Polygon(points) self.region.setWidth(2) self.region.draw(self.win) self.piece = Circle(Point(self.X, self.Y), self.edgeLen / 2) def undraw(self): self.region.undraw() self.piece.undraw() def clickIn(self, x, y): dv = Vector([x - self.X, y - self.Y]) limit = halfSq3 * self.edgeLen for v in HexBlock.Vec: if abs(v * dv) > limit: return False return True def placePiece(self, player): if self.player == None: self.piece.setFill(player.getColor()) self.piece.draw(self.win) self.player = player.getNum() return True else: return False def removePiece(self): if self.player != None: self.player = None self.piece.undraw() return True else: return False def getCenter(self): return self.X, self.Y def getPlayer(self): return self.player
def newAABB(self, obj, owner): obj.tl = Vector(99999, -9999, -999999) obj.br = Vector(-99999, 9999, 999999) for mesh in owner.getComponentsByType(MeshComponent): for triangle in mesh.triangles: for vertex in triangle: obj.tl.x = min(vertex[0], obj.tl.x) obj.tl.y = max(vertex[1], obj.tl.y) obj.tl.z = max(vertex[2], obj.tl.z) obj.br.x = max(vertex[0], obj.br.x) obj.br.y = min(vertex[1], obj.br.y) obj.br.z = min(vertex[2], obj.br.z)
def eovsa_array(): ''' Define EOVSA antenna array, which consists of tabulated E,N,U locations of 15 antennas plus "array center", latitude, longitude and elevation of array center. Returns AIPY AntennaArray object. ''' global lat mperns = 0.299792458 # Meters per nanosecond # Define antenna ENU locations. Ant 16 is the test input (0,0,0). # Divide by mperns to convert m to ns. ante = numpy.array([ 187.86, 196.15, 175.11, 197.96, 194.11, 147.42, 266.83, 98.95, 20.35, 167.43, -442.00, 640.22, -329.06, -631.00, -213.00, 0.0 ]) / mperns antn = numpy.array([ 71.74, 75.14, 77.39, 50.25, 108.86, 35.91, 67.10, 169.34, -218.49, 280.78, -138.59, -355.82, 861.82, -184.00, -187.00, 0.0 ]) / mperns antu = numpy.zeros(16) lng = -118.286953 * numpy.pi / 180 # OVSA Longitude (radians) elev = 1207.0 # OVSA Elevation (meters) clat = cos(lat) slat = sin(lat) # Latitude rotation matrix to convert ENU to XYZ latrot = mat([[0, -slat, clat], [1, 0, 0], [0, clat, slat]]) f = numpy.array([1.0]) beam = aipy.phs.Beam(f) ants = [] for i in range(16): enu = Vector([ante[i], antn[i], antu[i]]) x, y, z = enu.rotate(latrot).get() # Apply (add) any baseline corrections xp, yp, zp = bl_cor(x, y, z, i) ants.append(aipy.phs.Antenna(xp, yp, zp, beam)) aa = aipy.phs.AntennaArray(ants=ants, location=(lat, lng, elev)) aa.horizon = '10:30:00' aa.compute_pressure() # Create some standard sources for the source catalog srcs = [] srcs.append(aipy.amp.RadioSpecial('Sun')) srcs.append(aipy.amp.RadioSpecial('Moon')) cat = aipy.amp.SrcCatalog(srcs) cat.compute(aa) # Attach catalog to aa object aa.cat = cat return aa
def __init__(self, pos, shape, team=1, moveSpeed = 50.0, moveDir=None): #General self.collisionType = None #All objects are alive/enabled by default. self.alive = True #Objects position (the center) self.pos = Vector(pos) #The objects shape, used for collision detection self.shape = shape self.moveSpeed = moveSpeed if not moveDir: self.moveDir = Vector(0,0) else: self.moveDir = Vector(moveDir) #Velocity is the normalized direction scaled by the speed #TODO: calculate on update? if not self.moveDir.isNullVector(): #self.moveDir.normalize() self.vel = self.moveDir.getNormalized() * self.moveSpeed else: self.vel = Vector(0,0) #Keep track of where the objects wants to go next self.requestedPos = pos #Keep track of which direction the object is 'facing' self.orientation = None #Set up the animation object self.frames = [] #TODO: this is temporary for testing anim = animation.TestAnimation(size = shape.getSize()) self.animationPlayer = animation.AnimationPlayer(anim, 1.0, True) #set the team property self.team = team #Turning self.turning = False self.turnTime = 0.05 self.turnTimer = 0
def eovsa_array(): ''' Define EOVSA antenna array, which consists of tabulated E,N,U locations of 15 antennas plus "array center", latitude, longitude and elevation of array center. Returns AIPY AntennaArray object. ''' global lat mperns = 0.299792458 # Meters per nanosecond # Define antenna ENU locations. Ant 16 is the test input (0,0,0). # Divide by mperns to convert m to ns. ante = numpy.array([187.86, 196.15, 175.11, 197.96, 194.11, 147.42, 266.83, 98.95, 20.35, 167.43, -442.00, 640.22, -329.06, -631.00, -213.00, 0.0])/mperns antn = numpy.array([71.74, 75.14, 77.39, 50.25, 108.86, 35.91, 67.10, 169.34, -218.49, 280.78, -138.59, -355.82, 861.82, -184.00, -187.00, 0.0])/mperns antu = numpy.zeros(16) lng = -118.286953*numpy.pi/180 # OVSA Longitude (radians) elev = 1207.0 # OVSA Elevation (meters) clat = cos(lat) slat = sin(lat) # Latitude rotation matrix to convert ENU to XYZ latrot = mat([[0, -slat, clat],[1, 0, 0],[0, clat, slat]]) f = numpy.array([1.0]) beam = aipy.phs.Beam(f) ants = [] for i in range(16): enu = Vector([ante[i], antn[i], antu[i]]) x, y, z = enu.rotate(latrot).get() # Apply (add) any baseline corrections xp, yp, zp = bl_cor(x,y,z,i) ants.append(aipy.phs.Antenna(xp,yp,zp,beam)) aa = aipy.phs.AntennaArray(ants=ants,location=(lat, lng, elev)) aa.horizon='10:30:00' aa.compute_pressure() # Create some standard sources for the source catalog srcs = [] srcs.append(aipy.amp.RadioSpecial('Sun')) srcs.append(aipy.amp.RadioSpecial('Moon')) cat = aipy.amp.SrcCatalog(srcs) cat.compute(aa) # Attach catalog to aa object aa.cat = cat return aa
def requestMove(self, direction): """Indicate when preferred direction this object wants to go""" assert direction is not None if direction != (0, 0): normalizedOrientation = self.orientation.getNormalized() normalizedDirection = Vector(direction).getNormalized() if normalizedOrientation == normalizedDirection: #only move if facing the right direction, else turn #update the direction self.moveDir = Vector(direction) self.vel = self.moveDir.getNormalized()*self.moveSpeed self.turning = False #update the objects velocity #TODO: what if the move direction is 0 vector? #if not self.moveDir.isNullVector(): #self.moveDir.normalize() #self.vel = self.moveDir.getNormalized()*self.moveSpeed #else: #self.vel = Vector(0,0) else: self.turning = True self.vel = Vector(0,0) self.turn(Vector(direction)) else: #not trying to move self.vel = Vector(0,0) self.turning = False
def __init__(self, pixels, label): self.pixels = pixels self.label = label self.label_vec = Vector.zeros(CLASS_COUNT) self.label_vec[self.label] = 1.0 self._features = None self.features()
def clickIn(self, x, y): dv = Vector([x - self.X, y - self.Y]) limit = halfSq3 * self.edgeLen for v in HexBlock.Vec: if abs(v * dv) > limit: return False return True
def __init__(self, image_filename, levelmap): self.levelmap = levelmap self.__img = util.load_image(image_filename, False, None) order = range(8) delay = 4 # each phase of the animation lasts 6 frames offset = Vector(0,16) # the "position-point" of the hero is on # his left elbow... self.size = 16 self.__walk_down = Animation(order) for down_rect in [ (4+i*24, 0, 16, 31) for i in range(8) ]: self.__walk_down.add_frame(self.__img, down_rect, delay, offset) self.__walk_up = Animation(order) for up_rect in [ (4+i*24, 32, 16, 31) for i in range(8) ]: self.__walk_up.add_frame(self.__img, up_rect, delay, offset) self.__walk_left = Animation(order) for left_rect in [ (4+i*24, 64, 16, 31) for i in range(8) ]: self.__walk_left.add_frame(self.__img, left_rect, delay, offset) self.__walk_right = Animation(order) for right_rect in [ (4+i*24, 96, 16, 31) for i in range(8) ]: self.__walk_right.add_frame(self.__img, right_rect, delay, offset) # initial values self.state = self.DOWN_WALK # Coordinates are relative to the map - not to the screen! self.pos = Vector(0,0) self.speed = 2
def deserialize(ser): num_labels = len(ser['nodes']) num_weights = len(ser['nodes'][0]['weights']) layer = PerceptronLayer(num_labels, num_weights, activation.from_name(ser['activation'])) for node_ser, node in zip(ser['nodes'], layer.nodes): node.weights = Vector(node_ser['weights']) node.bias = node_ser['bias'] return layer
def __init__(self, position=Vector(0, 0, 0), velocity=Vector(0, 0, 0), acceleration=Vector(0, 0, 0), a_position=Vector(0, 0, 0), a_velocity=Vector(0, 0, 0), a_acceleration=Vector(0, 0, 0), bounded=True): # , anchor=Vector(0,0,0)): super().__init__() # Linear self.oldS = Vector(0, 0, 0) self.S = position self.V = velocity self.A = acceleration # Rotational # Ie, rotation around x axis, y axis, z axis (euler angles) # Very simple, temporary code. # Note that this is in degrees self.THETA = a_position # theta, phi, self.OMEGA = a_velocity self.ALPHA = a_acceleration self.bounded = bounded
def handle_aiming_action(self, key): self.hero.set_state("moving") if (key in self.movement_keys.keys()): vector = Vector(self.movement_keys[key][0], self.movement_keys[key][1]) zap = Zap(self.hero.x, self.hero.y) self.add_zap_at_vector(zap, vector) else: return True
class Perceptron: def __init__(self, layer, num_weights): self.layer = layer self.weights = Vector(random.gauss(0, 0.01) for _ in xrange(num_weights)) self.bias = random.gauss(0, 0.01) def feed_forward(self, example): """ Take inner product of weights and example, pass through activation function """ return self.layer.activation_fn.calculate((self.weights.dot(example)) + self.bias)
def features(self): """ Returns a dict from features names to values: - One features for each pixel (e.g. (4,3) -> 1) - components=1 - components=2 - components=3 - Other features... """ if not self._features: width = len(self.pixels[0]) height = len(self.pixels) self._features = Vector(self.pixels[i / width][i % width] / 256.0 for i in xrange(width * height)) return self._features
def addSVAComponent(self, position=Vector(0, 0, 0), velocity=Vector(0, 0, 0), acceleration=Vector(0, 0, 0), a_position=Vector(0, 0, 0), a_velocity=Vector(0, 0, 0), a_acceleration=Vector(0, 0, 0), bounded=True): self.addComponent( SVAComponent(position, velocity, acceleration, a_position, a_velocity, a_acceleration, bounded))
def locate(self, p): x, y = p.getX(), p.getY() if self.size == 1: if self.grid[0][0].clickIn(x, y): return (0, 0) else: return () elif self.size == 2: cord1 = 0 cord2 = 0 else: dv = Vector([x - self.Xo, y - self.Yo]) prod1 = dv * HexBoard.Vec[1] prod2 = dv * HexBoard.Vec[0] if halfSq3 * dv[1] + 0.5 * dv[0] > 0: param1 = -1 #rotate 30 degree counter-clockwise else: param1 = 1 if halfSq3 * dv[1] - 0.5 * dv[0] < 0: param2 = -1 #rotate 30 degree clockwise else: param2 = 1 cord1 = int((prod1 + param1 * math.sqrt( (dv * dv - prod1 * prod1) / 3)) / (sq3 * self.gridLen)) cord2 = int((prod2 + param2 * math.sqrt( (dv * dv - prod2 * prod2) / 3)) / (sq3 * self.gridLen)) if not (0 <= cord1 < self.size and 0 <= cord2 < self.size): return () if self.grid[cord1][cord2].clickIn(x, y): return (cord1, cord2) elif cord1 + 1 < self.size and self.grid[cord1 + 1][cord2].clickIn( x, y): return (cord1 + 1, cord2) elif cord2 + 1 < self.size and self.grid[cord1][cord2 + 1].clickIn( x, y): return (cord1, cord2 + 1) elif cord1 + 1 < self.size and cord2 + 1 < self.size and self.grid[ cord1 + 1][cord2 + 1].clickIn(x, y): return (cord1 + 1, cord2 + 1) else: return ()
def update(self, _): # First, update for changes in SVA for e, c in self.eman.pairsForType(CollisionComponent): if c.AABB: self.newAABB(c, e) for e0, c0 in self.eman.pairsForType(CollisionComponent): if c0.active: for e1, c1 in self.eman.pairsForType(CollisionComponent): if e0 is not e1 and c1.active and c1.type_ in c0.typeCollide: if c0.AABB and c1.AABB: bCollides = self.collidesWithAABB(c0, c1) #bCollides = self.collidesWithTriangles(c0, c1) else: # Triangle intersections, baby! bCollides = self.collidesWithTriangles(c0, c1) if bCollides: s = e0.getSingleComponentByType(SVAComponent) s.A = Vector(x=0, y=1, z=0, w=1) print(e0, " collides with ", e1) print(int(round(time.time() * 1000)))
class HexBoard: Vec = [Vector(v) for v in [(halfSq3, 0.5), (halfSq3, -0.5)]] adVec = [ Vector(v) for v in [(1, 0), (0, 1), (-1, 0), (0, -1), (-1, 1), (1, -1)] ] def __init__(self, win, size, gridLen, origin): self.active = True self.mark1, self.mark2 = [0] * size, [0] * size self.win = win self.size = size self.gridLen = gridLen self.grid = [] self.moveStack = Stack(size * size) for i in range(size): self.grid.append([]) self.Xo, self.Yo = origin.getX(), origin.getY() pio = self.Xo, self.Yo for i in range(size): newCenter = pio for j in range(size): newGrid = HexBlock(win, gridLen, newCenter) self.grid[i].append(newGrid) newCenter = (newCenter[0] + 1.5 * gridLen, newCenter[1] + halfSq3 * gridLen) pio = (pio[0] + 1.5 * gridLen, pio[1] - halfSq3 * gridLen) self.drawOuterLines() def undraw(self): if not self.active: return map(lambda item: item.undraw, self.lines) map(lambda row: map(lambda item: item.undraw(), row), self.grid) self.active = False def drawOuterLines(self): self.lines = [] p1 = Point(self.Xo - self.gridLen * 2, self.Yo) p2 = Point(self.Xo + 1.5 * (self.size - 1) * self.gridLen, self.Yo + halfSq3 * (self.size + 1.0 / 3) * self.gridLen) p3 = Point(self.Xo + (3 * self.size - 1) * self.gridLen, self.Yo) p4 = Point(self.Xo + 1.5 * (self.size - 1) * self.gridLen, self.Yo - halfSq3 * (self.size + 1.0 / 3) * self.gridLen) ps = [p1, p2, p3, p4] for i in range(4): self.lines.append(Line(ps[i], ps[(i + 1) % 4])) if i % 2: self.lines[i].setOutline("red") else: self.lines[i].setOutline("blue") self.lines[i].setWidth(2) self.lines[i].draw(self.win) def locate(self, p): x, y = p.getX(), p.getY() if self.size == 1: if self.grid[0][0].clickIn(x, y): return (0, 0) else: return () elif self.size == 2: cord1 = 0 cord2 = 0 else: dv = Vector([x - self.Xo, y - self.Yo]) prod1 = dv * HexBoard.Vec[1] prod2 = dv * HexBoard.Vec[0] if halfSq3 * dv[1] + 0.5 * dv[0] > 0: param1 = -1 #rotate 30 degree counter-clockwise else: param1 = 1 if halfSq3 * dv[1] - 0.5 * dv[0] < 0: param2 = -1 #rotate 30 degree clockwise else: param2 = 1 cord1 = int((prod1 + param1 * math.sqrt( (dv * dv - prod1 * prod1) / 3)) / (sq3 * self.gridLen)) cord2 = int((prod2 + param2 * math.sqrt( (dv * dv - prod2 * prod2) / 3)) / (sq3 * self.gridLen)) if not (0 <= cord1 < self.size and 0 <= cord2 < self.size): return () if self.grid[cord1][cord2].clickIn(x, y): return (cord1, cord2) elif cord1 + 1 < self.size and self.grid[cord1 + 1][cord2].clickIn( x, y): return (cord1 + 1, cord2) elif cord2 + 1 < self.size and self.grid[cord1][cord2 + 1].clickIn( x, y): return (cord1, cord2 + 1) elif cord1 + 1 < self.size and cord2 + 1 < self.size and self.grid[ cord1 + 1][cord2 + 1].clickIn(x, y): return (cord1 + 1, cord2 + 1) else: return () def placePiece(self, cord, player): success = self.grid[cord[0]][cord[1]].placePiece(player) if not success: return False n = player.getNum() if n == 1: self.mark1[cord[0]] += 1 elif n == 2: self.mark2[cord[1]] += 1 self.moveStack.push(HexMove(player, cord)) return success def removePiece(self): cord = self.moveStack.pop() if cord != None: cord = cord.getPos() else: return False n = self.grid[cord[0]][cord[1]].getPlayer() success = self.grid[cord[0]][cord[1]].removePiece() if not success: return False if n == 1: self.mark1[cord[0]] -= 1 elif n == 2: self.mark2[cord[1]] = -1 return success def redo(self): item = self.moveStack.redo() if item != None: player = item.getPlayer() cord = item.getPos() success = self.grid[cord[0]][cord[1]].placePiece(player) if not success: return False n = player.getNum() if n == 1: self.mark1[cord[0]] += 1 elif n == 2: self.mark2[cord[1]] += 1 return False def winner(self): if 0 in self.mark1 and 0 in self.mark2: return None if self.scan(1): return 1 elif self.scan(2): return 2 else: return None def inRange(self, pos): return 0 <= pos[0] < self.size and 0 <= pos[1] < self.size def getAdjacent(self, iset): adjacent = set() for item in iset: for v in HexBoard.adVec: candidate = tuple(map(sum, zip(item, v))) if self.inRange(candidate): adjacent.add(candidate) return adjacent def scan(self, player): adjacent = set() for j in range(self.size): iset = set() for i in range(self.size): if player == 1: p = self.grid[j][i].getPlayer() additem = (j, i) elif player == 2: p = self.grid[i][j].getPlayer() additem = (i, j) if player == p: iset.add(additem) if iset.isdisjoint(adjacent) and j > 0: return False adjacent = self.getAdjacent(iset) return True def getGrid(self): return self.grid def getStack(self): return self.moveStack
elif option == 1: if vectores.count() == 0: if not os.path.exists('data/vectores.txt'): print 'Copie y pegue sus 2000 vectores en la carpeta data, yo le espero' time.sleep(3.5) print 'yamete kudasai onii-chan' else: arch = open('data/vectores.txt', 'r') data = arch.readlines() arch.close() #begin creation and insertion for vec_txt in data: vectores.insert_one(Vector(vec_txt).__dict__) del arch, data #release print 'data stored in mongodb!' else: print 'mongodb already contains data' elif option == 2: vec_cursor = vectores.find() try: for i in range(5): pprint(vec_cursor.next()) except StopIteration:
class Direction(object): UP = Vector(0, -1) DOWN = Vector(0, 1) LEFT = Vector(-1, 0) RIGHT = Vector(1, 0)
def _compute_one_parameter(self, param_value, index): source_position = np.array([get_scarray_value(self.args.source_position_x, index), get_scarray_value(self.args.source_position_y, index), get_scarray_value(self.args.source_position_z, index)]) axis = Vector(x_angle=get_scarray_value(self.args.axis_angle_x, index), y_angle=get_scarray_value(self.args.axis_angle_y, index), z_angle=get_scarray_value(self.args.axis_angle_z, index), position=[get_scarray_value(self.args.center_position_x, index), 0, get_scarray_value(self.args.center_position_z, index)]) detector = Vector(x_angle=get_scarray_value(self.args.detector_angle_x, index), y_angle=get_scarray_value(self.args.detector_angle_y, index), z_angle=get_scarray_value(self.args.detector_angle_z, index), position=[get_scarray_value(self.args.detector_position_x, index), get_scarray_value(self.args.detector_position_y, index), get_scarray_value(self.args.detector_position_z, index)]) volume_angle = Vector(x_angle=get_scarray_value(self.args.volume_angle_x, index), y_angle=get_scarray_value(self.args.volume_angle_y, index), z_angle=get_scarray_value(self.args.volume_angle_z, index)) z = self.args.z if self.args.z_parameter == 'z': z = param_value elif self.args.z_parameter == 'axis-angle-x': axis.x_angle = param_value elif self.args.z_parameter == 'axis-angle-y': axis.y_angle = param_value elif self.args.z_parameter == 'axis-angle-z': axis.z_angle = param_value elif self.args.z_parameter == 'volume-angle-x': volume_angle.x_angle = param_value elif self.args.z_parameter == 'volume-angle-y': volume_angle.y_angle = param_value elif self.args.z_parameter == 'volume-angle-z': volume_angle.z_angle = param_value elif self.args.z_parameter == 'detector-angle-x': detector.x_angle = param_value elif self.args.z_parameter == 'detector-angle-y': detector.y_angle = param_value elif self.args.z_parameter == 'detector-angle-z': detector.z_angle = param_value elif self.args.z_parameter == 'detector-position-x': detector.position[0] = param_value elif self.args.z_parameter == 'detector-position-y': detector.position[1] = param_value elif self.args.z_parameter == 'detector-position-z': detector.position[2] = param_value elif self.args.z_parameter == 'source-position-x': source_position[0] = param_value elif self.args.z_parameter == 'source-position-y': source_position[1] = param_value elif self.args.z_parameter == 'source-position-z': source_position[2] = param_value elif self.args.z_parameter == 'center-position-x': axis.position[0] = param_value elif self.args.z_parameter == 'center-position-z': axis.position[2] = param_value else: raise RuntimeError("Unknown z parameter '{}'".format(self.args.z_parameter)) points = get_extrema(self.args.x_region, self.args.y_region, z) if self.args.z_parameter != 'z': points_upper = get_extrema(self.args.x_region, self.args.y_region, z + 1) points = np.hstack((points, points_upper)) tomo_angle = float(index) / self.args.number * self.args.overall_angle xe, ye = compute_detector_pixels(points, source_position, axis, volume_angle, detector, tomo_angle) return compute_detector_region(xe, ye, (self.args.height, self.args.width), overhead=self.args.projection_margin)
class Hero: # states: # Maybe these should be replaced by the direction-constants below (UP_WALK, UP_STAND, DOWN_WALK, DOWN_STAND, LEFT_WALK, LEFT_STAND, RIGHT_WALK, RIGHT_STAND) = range(8) # directions: NO_DIRECTION = Vector(0,0) LEFT = Vector(-1,0) RIGHT = Vector(1,0) UP = Vector(0,-1) DOWN = Vector(0,1) def __init__(self, image_filename, levelmap): self.levelmap = levelmap self.__img = util.load_image(image_filename, False, None) order = range(8) delay = 4 # each phase of the animation lasts 6 frames offset = Vector(0,16) # the "position-point" of the hero is on # his left elbow... self.size = 16 self.__walk_down = Animation(order) for down_rect in [ (4+i*24, 0, 16, 31) for i in range(8) ]: self.__walk_down.add_frame(self.__img, down_rect, delay, offset) self.__walk_up = Animation(order) for up_rect in [ (4+i*24, 32, 16, 31) for i in range(8) ]: self.__walk_up.add_frame(self.__img, up_rect, delay, offset) self.__walk_left = Animation(order) for left_rect in [ (4+i*24, 64, 16, 31) for i in range(8) ]: self.__walk_left.add_frame(self.__img, left_rect, delay, offset) self.__walk_right = Animation(order) for right_rect in [ (4+i*24, 96, 16, 31) for i in range(8) ]: self.__walk_right.add_frame(self.__img, right_rect, delay, offset) # initial values self.state = self.DOWN_WALK # Coordinates are relative to the map - not to the screen! self.pos = Vector(0,0) self.speed = 2 def stand(self): if self.state == Hero.DOWN_WALK: self.state = Hero.DOWN_STAND elif self.state == Hero.UP_WALK: self.state = Hero.UP_STAND elif self.state == Hero.LEFT_WALK: self.state = Hero.LEFT_STAND elif self.state == Hero.RIGHT_WALK: self.state = Hero.RIGHT_STAND def tick(self): # TODO beautify method (make some lines shorter) # Cancel movement, if hero is standing if self.state in [Hero.LEFT_STAND, Hero.RIGHT_STAND, Hero.UP_STAND, Hero.DOWN_STAND]: return # Otherwise: Determine direction direction = { Hero.LEFT_WALK : Hero.LEFT, Hero.RIGHT_WALK : Hero.RIGHT, Hero.UP_WALK : Hero.UP, Hero.DOWN_WALK : Hero.DOWN }[self.state] corners = self.get_corners(direction) delta = util.vec_mult(direction, self.speed) dest_tiles = [self.levelmap.pixel_pos_to_tile_pos( util.vec_add(c, delta)) for c in corners] tiletypes =\ [self.levelmap.get_tile_type(t) == LevelMap.LevelMap.FLOOR for t in dest_tiles] if reduce(lambda a, b: a and b, tiletypes): self.pos.add(delta) else: self.move_to_edge(direction) def get_bounds(self): # Maybe the use of this function should be replaced by "get_corners" return (self.pos.x, self.pos.y, self.size, self.size) def get_corners(self, direction): upper_left = self.pos upper_right = util.vec_add(self.pos, Vector(self.size-1, 0)) lower_left = util.vec_add(self.pos, Vector(0, self.size-1)) lower_right = util.vec_add(self.pos, Vector(self.size-1, self.size-1)) if direction == Hero.LEFT: return [upper_left, lower_left] elif direction == Hero.RIGHT: return [upper_right, lower_right] elif direction == Hero.UP: return [upper_left, upper_right] elif direction == Hero.DOWN: return [lower_left, lower_right] else: return [] def move_to_edge(self, direction): distance_left = self.pos.x % self.levelmap.tilesize distance_up = self.pos.y % self.levelmap.tilesize if direction == Hero.LEFT: self.pos.x -= distance_left elif direction == Hero.RIGHT: self.pos.x += (self.levelmap.tilesize - self.size - distance_left) elif direction == Hero.UP: self.pos.y -= distance_up elif direction == Hero.DOWN: self.pos.y += (self.levelmap.tilesize - self.size - distance_up) def show(self, screen, offset): pos = util.vec_add(self.pos, offset) offset_pos = (pos.x, pos.y - 16) if self.state == Hero.DOWN_WALK: self.__walk_down.show(screen, pos) elif self.state == Hero.UP_WALK: self.__walk_up.show(screen, pos) elif self.state == Hero.LEFT_WALK: self.__walk_left.show(screen, pos) elif self.state == Hero.RIGHT_WALK: self.__walk_right.show(screen, pos) elif self.state == Hero.DOWN_STAND: screen.blit(self.__img, offset_pos, (4, 0, 16, 31)) elif self.state == Hero.UP_STAND: screen.blit(self.__img, offset_pos, (4, 32, 16, 31)) elif self.state == Hero.LEFT_STAND: screen.blit(self.__img, offset_pos, (4, 64, 16, 31)) elif self.state == Hero.RIGHT_STAND: screen.blit(self.__img, offset_pos, (4, 96, 16, 31))
def __init__(self, layer, num_weights): self.layer = layer self.weights = Vector(random.gauss(0, 0.01) for _ in xrange(num_weights)) self.bias = random.gauss(0, 0.01)
def feed_forward(self, example): return Vector(node.feed_forward(example) for node in self.nodes)
def _compute_one_parameter(self, param_value, index): source_position = np.array([ get_scarray_value(self.args.source_position_x, index), get_scarray_value(self.args.source_position_y, index), get_scarray_value(self.args.source_position_z, index) ]) axis = Vector(x_angle=get_scarray_value(self.args.axis_angle_x, index), y_angle=get_scarray_value(self.args.axis_angle_y, index), z_angle=get_scarray_value(self.args.axis_angle_z, index), position=[ get_scarray_value(self.args.center_position_x, index), 0, get_scarray_value(self.args.center_position_z, index) ]) detector = Vector(x_angle=get_scarray_value(self.args.detector_angle_x, index), y_angle=get_scarray_value(self.args.detector_angle_y, index), z_angle=get_scarray_value(self.args.detector_angle_z, index), position=[ get_scarray_value(self.args.detector_position_x, index), get_scarray_value(self.args.detector_position_y, index), get_scarray_value(self.args.detector_position_z, index) ]) volume_angle = Vector( x_angle=get_scarray_value(self.args.volume_angle_x, index), y_angle=get_scarray_value(self.args.volume_angle_y, index), z_angle=get_scarray_value(self.args.volume_angle_z, index)) z = self.args.z if self.args.z_parameter == 'z': z = param_value elif self.args.z_parameter == 'axis-angle-x': axis.x_angle = param_value elif self.args.z_parameter == 'axis-angle-y': axis.y_angle = param_value elif self.args.z_parameter == 'axis-angle-z': axis.z_angle = param_value elif self.args.z_parameter == 'volume-angle-x': volume_angle.x_angle = param_value elif self.args.z_parameter == 'volume-angle-y': volume_angle.y_angle = param_value elif self.args.z_parameter == 'volume-angle-z': volume_angle.z_angle = param_value elif self.args.z_parameter == 'detector-angle-x': detector.x_angle = param_value elif self.args.z_parameter == 'detector-angle-y': detector.y_angle = param_value elif self.args.z_parameter == 'detector-angle-z': detector.z_angle = param_value elif self.args.z_parameter == 'detector-position-x': detector.position[0] = param_value elif self.args.z_parameter == 'detector-position-y': detector.position[1] = param_value elif self.args.z_parameter == 'detector-position-z': detector.position[2] = param_value elif self.args.z_parameter == 'source-position-x': source_position[0] = param_value elif self.args.z_parameter == 'source-position-y': source_position[1] = param_value elif self.args.z_parameter == 'source-position-z': source_position[2] = param_value elif self.args.z_parameter == 'center-position-x': axis.position[0] = param_value elif self.args.z_parameter == 'center-position-z': axis.position[2] = param_value else: raise RuntimeError("Unknown z parameter '{}'".format( self.args.z_parameter)) points = get_extrema(self.args.x_region, self.args.y_region, z) if self.args.z_parameter != 'z': points_upper = get_extrema(self.args.x_region, self.args.y_region, z + 1) points = np.hstack((points, points_upper)) tomo_angle = float(index) / self.args.number * self.args.overall_angle xe, ye = compute_detector_pixels(points, source_position, axis, volume_angle, detector, tomo_angle) return compute_detector_region(xe, ye, (self.args.height, self.args.width), overhead=self.args.projection_margin)
def __init__(self, x, y): super(Player, self).__init__(x*40, y*40, 40, 40) self.velocity = Vector() self.terminal_velocity = 5.0 self.airborne = False
class AbstractObject(object): """All game world objects are ultimately derived from this class. Contains a variety of useful functions used for movement and collision detection""" def __init__(self, pos, shape, team=1, moveSpeed = 50.0, moveDir=None): #General self.collisionType = None #All objects are alive/enabled by default. self.alive = True #Objects position (the center) self.pos = Vector(pos) #The objects shape, used for collision detection self.shape = shape self.moveSpeed = moveSpeed if not moveDir: self.moveDir = Vector(0,0) else: self.moveDir = Vector(moveDir) #Velocity is the normalized direction scaled by the speed #TODO: calculate on update? if not self.moveDir.isNullVector(): #self.moveDir.normalize() self.vel = self.moveDir.getNormalized() * self.moveSpeed else: self.vel = Vector(0,0) #Keep track of where the objects wants to go next self.requestedPos = pos #Keep track of which direction the object is 'facing' self.orientation = None #Set up the animation object self.frames = [] #TODO: this is temporary for testing anim = animation.TestAnimation(size = shape.getSize()) self.animationPlayer = animation.AnimationPlayer(anim, 1.0, True) #set the team property self.team = team #Turning self.turning = False self.turnTime = 0.05 self.turnTimer = 0 def onCollide(self, object): """Handles collision""" pass #print object #if object.collisionType == 'PROJECTILE': # print 'proj' def orientationToString(self): #converts the orientation to a string #makes it easier for animation #if self.orientation == None: #FIX FOR IF THERE IS NO ORIENTATION # return 'north' string = '' if self.orientation[0] == 0 and self.orientation[1] < 0: string = 'UP' elif self.orientation[0] == 0 and self.orientation[1] > 0: string = 'DOWN' elif self.orientation[0] > 0 and self.orientation[1] == 0: string = 'RIGHT' elif self.orientation[0] < 0 and self.orientation[1] == 0: string = 'LEFT' elif self.orientation[0] < 0 and self.orientation[1] < 0: string = 'UPLEFT' elif self.orientation[0] > 0 and self.orientation[1] > 0: string = 'DOWNRIGHT' elif self.orientation[0] < 0 and self.orientation[1] > 0: string = 'DOWNLEFT' elif self.orientation[0] > 0 and self.orientation[1] < 0: string = 'UPRIGHT' return string def draw(self, screen, offset): #draw the animation, centered at the objects position # and offset according to the location of the camera self.animationPlayer.draw(screen, self.getPos()+offset) def setPos(self, pos): self.pos = Vector(pos) def getPos(self): return self.pos def getPosInTime(self, time): """Calculate the objects position in 'time' as a function of its current position and velocity.""" return self.pos + self.vel*time # # def getRect(self): # #return (self.pos[0],self.pos[1], # # self.size[0],self.size[1]) # # return Rect(self.pos, self.size) def getRequestedPos(self): return self.requestedPos # def getVelocity(self): # return self.moveSpeed # def isCollision(self, o,requested=False): # #request=True means we check requested positions # """Check if this object's rect overlaps the other's rect""" # # if requested: # ax1,ay1 = self.requestedPos # else: # ax1,ay1 = self.pos # ax2,ay2 = ax1+self.size[0],ay1+self.size[1] # # if requested: # bx1,by1 = o.requestedPos # else: # bx1,by1 = o.pos # bx2,by2 = bx1+o.size[0],by1+o.size[1] # # if ax1 < bx2 and ax2 > bx1 and ay1 < by2 and ay2 > by1: # return True # else: # return False def requestMove(self, direction): """Indicate when preferred direction this object wants to go""" assert direction is not None if direction != (0, 0): normalizedOrientation = self.orientation.getNormalized() normalizedDirection = Vector(direction).getNormalized() if normalizedOrientation == normalizedDirection: #only move if facing the right direction, else turn #update the direction self.moveDir = Vector(direction) self.vel = self.moveDir.getNormalized()*self.moveSpeed self.turning = False #update the objects velocity #TODO: what if the move direction is 0 vector? #if not self.moveDir.isNullVector(): #self.moveDir.normalize() #self.vel = self.moveDir.getNormalized()*self.moveSpeed #else: #self.vel = Vector(0,0) else: self.turning = True self.vel = Vector(0,0) self.turn(Vector(direction)) else: #not trying to move self.vel = Vector(0,0) self.turning = False def turn(self, direction): """Use cross product to find the best direction and turns 45 degrees""" if self.orientation.getNormalized() != direction.getNormalized(): #prevents over turning incase time is large if self.turnTimer >= self.turnTime: o = self.orientation.getNormalized() d = direction.getNormalized() value = o[0]*d[1] - o[1]*d[0] sinCos = 0.707106781 #rotate 45 degrees so sin and cos are equal if value >= 0: x = self.orientation[0]*sinCos - self.orientation[1]*sinCos y = self.orientation[0]*sinCos + self.orientation[1]*sinCos else: x = self.orientation[0]*sinCos + self.orientation[1]*sinCos y = self.orientation[1]*sinCos - self.orientation[0]*sinCos #Smooths out all rounding errors if x > 0: x = 1 elif x < 0: x = -1 if y > 0: y = 1 elif y < 0: y = -1 self.orientation = Vector(x,y) self.turnTimer -= self.turnTime self.turn(direction) #turns again if time exceeds one turn, but dont want to overturn def updatePos(self, time): """Set the objects position equal to its requested position. Usually done after collision resolution""" self.pos = self.requestedPos def updateRequestedPos(self, time): """Update the objects requested position, done before collision resolution""" self.requestedPos = self.getPosInTime(time) def update(self, time): #TODO: animations should be updated after collision detection #update the animation if self.animationPlayer: self.animationPlayer.update(time) #update turning clock if self.turning: self.turnTimer += time