def __init__(self, whichType, position=[0, 0], velocity=[0, 0], acceleration=[0, 0], flipped=False, projectile=False): """ Creates a basic Entity of a specific type. """ Object.__init__(self, whichType, position, flipped=flipped) Entity.Entities.append(self) Object.Objects.pop(-1) #Collision self.collideState = None self.collidingLeft, self.collidingRight, self.collidingTop, self.collidingBottom = [ False ] * 4 #Physics self.acceleration = acceleration self.velocity = velocity self.wallSliding = False self.slidingSide = None self.projectile = projectile self.destroy = False
def __init__(self, path=None): self._startTime = time.time() global globalAppServer assert globalAppServer is None, 'more than one app server; or __init__() invoked more than once' globalAppServer = self ConfigurableForServerSidePath.__init__(self) Object.__init__(self) if path is None: path = os.path.dirname(__file__) #os.getcwd() self._serverSidePath = os.path.abspath(path) self._webKitPath = os.path.abspath(os.path.dirname(__file__)) self._webwarePath = os.path.dirname(self._webKitPath) self._verbose = self.setting('Verbose') self._plugIns = [] self._reqCount = 0 self.checkForInstall() self.config() # cache the config self.printStartUpMessage() sys.setcheckinterval(self.setting('CheckInterval')) self._app = self.createApplication() self.loadPlugIns() self.running = 1 if self.isPersistent(): self._closeEvent = Event() self._closeThread = Thread(target=self.closeThread) ## self._closeThread.setDaemon(1) self._closeThread.start()
def __init__(self, whichType, position = None, velocity = None, acceleration = None, flipped = False, projectile = False): """ Creates a basic Entity of a specific type. """ Object.__init__(self, whichType, position, flipped = flipped) Entity.Entities.append(self) Object.Objects.pop(-1) #Collision self.collideState = None self.collidingLeft,self.collidingRight,self.collidingTop,self.collidingBottom = [False] * 4 #Physics self.acceleration = acceleration if acceleration == None: self.acceleration = Vector() self.velocity = velocity if velocity == None: self.velocity = Vector() self.wallSliding = False self.slidingSide = None self.projectile = projectile self.destroy = False
def __init__(self): Object.__init__(self) self.Temas = Temas("Todos") self.TemasSeleccion = Temas("Seleccion") self.Ubicaciones = Ubicaciones() self.Distancias = Distancias() self.Combinaciones = Combinaciones() self.Hitos = Hitos(self.Distancias) self.observers = [] self.HoraDesdeFiltro = "" self.HoraHastaFiltro = "" self.algoritmos = [ ("MT0-Todas las combinaciones", "generarCombinaciones_MT0", True), ("MT1-Randomización de hitos", "generarCombinaciones_MT1", True), ("MT2-Hitos ordenados por fecha", "generarCombinaciones_MT2", True), ("MT3-Orden por combinabilidad (desc)", "generarCombinaciones_MT3", True), ("MT4-Orden por combinabilidad (asc)", "generarCombinaciones_MT4", True), ("MT5-Orden por combinabilidad de temas (desc)", "generarCombinaciones_MT5", True) ] self.algoritmoDefault = "MT3-Orden por combinabilidad (desc)" self.__load_data()
def __init__(self, x=0, y=0, hp=100, textures=textures, w=w, h=h): Object.__init__(self, x, y, textures[0], w, h) self.texLeftRight = image.load(textures[0]).convert() self.texUpDown = image.load(textures[1]).convert() self.hp = hp self.speed = 2 self.mSpeed = 10
def __init__(self): Object.__init__(self) config = CNCConfig() self.units = config.ReadFloat("ProgramUnits", 1.0) # set to 25.4 for inches self.alternative_machines_file = config.Read("ProgramAlternativeMachinesFile", "") self.raw_material = RawMaterial() # // for material hardness - to determine feeds and speeds. machine_name = config.Read("ProgramMachine", "emc2b") self.machine = self.GetMachine(machine_name) import wx default_output_file = (wx.StandardPaths.Get().GetTempDir() + "/test.tap").replace("\\", "/") self.output_file = config.Read( "ProgramOutputFile", default_output_file ) # // NOTE: Only relevant if the filename does NOT follow the data file's name. self.output_file_name_follows_data_file_name = config.ReadBool( "OutputFileNameFollowsDataFileName", True ) # // Just change the extension to determine the NC file name self.python_program = "" self.path_control_mode = config.ReadInt("ProgramPathControlMode", PATH_CONTROL_UNDEFINED) self.motion_blending_tolerance = config.ReadFloat( "ProgramMotionBlendingTolerance", 0.0 ) # Only valid if m_path_control_mode == eBestPossibleSpeed self.naive_cam_tolerance = config.ReadFloat( "ProgramNaiveCamTolerance", 0.0 ) # Only valid if m_path_control_mode == eBestPossibleSpeed
def createAlienSpacShip(self,canvas:'Canvas Tkinter') -> Game: alienSpaceShip = Object('AlienSpaceShip', 50,50,25,'red',score=randint(1,4)*50) (x1, y1, x2, y2) = alienSpaceShip.getIdBox() size = x2-x1 alienSpaceShip.setDraw(canvas.create_polygon(x1, y1, x2, y2, x1, y1+0.2*size, x2, y2-size*0.5, x1, y2, fill=alienSpaceShip.getColor())) self.addAlienSpaceShip(alienSpaceShip) return self
def link(self): if not isinstance(self.return_type, str): return return_type = self.return_type self.return_type = Object() self.return_type.parse(return_type)
def __init__(self): Object.__init__(self) config = CNCConfig() self.units = config.ReadFloat("ProgramUnits", 1.0) # set to 25.4 for inches self.alternative_machines_file = config.Read( "ProgramAlternativeMachinesFile", "") self.raw_material = RawMaterial( ) #// for material hardness - to determine feeds and speeds. machine_name = config.Read("ProgramMachine", "emc2b") self.machine = self.GetMachine(machine_name) import wx default_output_file = (wx.StandardPaths.Get().GetTempDir() + "/test.tap").replace('\\', '/') self.output_file = config.Read( "ProgramOutputFile", default_output_file ) # // NOTE: Only relevant if the filename does NOT follow the data file's name. self.output_file_name_follows_data_file_name = config.ReadBool( "OutputFileNameFollowsDataFileName", True ) # // Just change the extension to determine the NC file name self.python_program = "" self.path_control_mode = config.ReadInt("ProgramPathControlMode", PATH_CONTROL_UNDEFINED) self.motion_blending_tolerance = config.ReadFloat( "ProgramMotionBlendingTolerance", 0.0) # Only valid if m_path_control_mode == eBestPossibleSpeed self.naive_cam_tolerance = config.ReadFloat( "ProgramNaiveCamTolerance", 0.0) # Only valid if m_path_control_mode == eBestPossibleSpeed
def new_game(): global player, inventory, game_msgs, game_state, dungeon_level #create object representing the player entity_component = Entity(5) GameState.player = Object(0, 0, '@', 'player', libtcod.white, blocks=True, entity=entity_component) GameState.player.level = 1 #generate map (at this point it's not drawn to the screen) dungeon_level = 1 Map.make_map() initialize_fov() game_state = 'playing' GameState.inventory = [] #create the list of game messages and their colors, starts empty GameState.game_msgs = [] #a warm welcoming message! GUI.message('Welcome stranger! Prepare to perish in the Tombs of the Ancient Kings.', libtcod.red) #initial equipment: a dagger equipment_component = Equipment(slot='right hand', power_bonus=2) obj = Object(0, 0, '-', 'dagger', libtcod.sky, equipment=equipment_component) GameState.inventory.append(obj) equipment_component.equip() obj.always_visible = True
def testeMutare(logic): # Testeaza functionalitatea de mutare objects = logic.domain.getObjects() newObj = Object(3, "test", "desc", 3, "loc3") logic.addObject(newObj) newObj = Object(4, "test", "desc", 4, "loc3") logic.addObject(newObj) newObj = Object(5, "test", "desc", 2.6, "loc5") logic.addObject(newObj) nrloc3 = 0 nrloc4 = 0 for obj in logic.domain.getObjects(): if obj.getLocatie() == "loc3": nrloc3 = nrloc3 + 1 if obj.getLocatie() == "loc4": nrloc4 = nrloc4 + 1 assert nrloc3 == 2 assert nrloc4 == 0 logic.moveObjects("loc3", "loc4") nrloc3 = 0 nrloc4 = 0 for obj in logic.domain.getObjects(): if obj.getLocatie() == "loc3": nrloc3 = nrloc3 + 1 if obj.getLocatie() == "loc4": nrloc4 = nrloc4 + 1 assert nrloc3 == 0 assert nrloc4 == 2
def insert_objects(self): test_object = Object('apple', 'green', 1, 450, 375, 'green_apple.jpg') self.object_list.add( test_object) # insert test object into environment test_object2 = Object('apple', 'red', 1, 600, 375, 'apple.png') self.object_list.add( test_object2) # insert test object into environment
def __init__(self, codigo, nombre, info, duracion): Object.__init__(self) self.codigo = codigo self.nombre = nombre self.duracion = duracion self.info = info
def __init__(self, origen, destino, distancia): Object.__init__(self) self.origen = origen self.destino = destino self.distancia = distancia
def __init__(self, caption, font, size, color, position, camera): quad_obj = Loader("./resources/models/quad.obj") self.font = Font(caption, font, color[0], color[1], color[2]) self.quad = Object(quad_obj, camera, self.font) self.quad.model['rotation'] = [0, math.pi / 2, 0] self.quad.translate(*position) self.quad.scale(size * 0.04 * len(caption) / 10, 1, size * 0.1 / 10)
def lookAtObject(self, item): if self.obj_window is None: self.obj_window = Object(item) self.obj_window.show() else: self.obj_window.close() self.obj_window = None
def __init__(self, distancias, horadesde="", horahasta=""): Object.__init__(self) self._items = [] self.position = -1 self.distancias = distancias self.horadesde = horadesde self.horahasta = horahasta
def place_stairs(x, y, char, name): stairs = Object(x, y, char, name, tcod.white, always_visible=True) if stairs.char == '<': settings.stairs_up = stairs else: settings.stairs_down = stairs settings.objects.append(stairs) stairs.send_to_back()
def loadBlenderProperties(self, object): Object.loadBlenderProperties(self, object) try: self.size = object.getProperty('size').getData() except AttributeError: # use the default size self.set_size() self.name = object.getName()
def __init__(self, name = '' ): Object.__init__( self, name ) # Electrical Stuff self.port_dict = {} self.net_dict = {} self.inst_dict = {} self.param_dict = {} self.port_name_list = []
def __init__(self, name=''): Object.__init__(self, name) # Electrical Stuff self.port_dict = {} self.net_dict = {} self.inst_dict = {} self.param_dict = {} self.port_name_list = []
def __init__(self, position, power, color, radius, camera): self.position = position self.power = power self.color = color self.radius = radius sphere_obj = Loader("./resources/models/sphere.obj") red_texture = Texture("./resources/textures/triangles_red.png") self.sphere = Object(sphere_obj, camera, red_texture, color=color) self.sphere.scale(radius, radius, radius) self.sphere.translate(position[0], position[1], position[2])
def __init__(self, mod=1.0, num_teeth=12): Object.__init__(self, 0) self.tm = geom.Matrix() self.numTeeth = num_teeth self.module = mod self.addendumOffset = 0.0 self.addendumMultiplier = 1.0 self.dedendumMultiplier = 1.0 self.pressureAngle = 0.34906585039886 # 20 degrees self.tipRelief = 0.05 self.color = cad.Color(128, 128, 128)
def __init__(self, distancias, horadesde="", horahasta=""): Object.__init__(self) self.hitos = Hitos(distancias, horadesde, horahasta) self.horadesde = horadesde self.horahasta = horahasta self.descripcion = "" self.distancias = distancias self.numero = Combinacion.numero Combinacion.numero = Combinacion.numero + 1
def loadObjects(self): # incarca obiectele din fisierul baza de date self.objects = [] dbfile = open(self.database, "r") for line in dbfile: line = line.strip().split(" ") newObj = Object(int(line[0]), line[1], line[2], float(line[3]), line[4]) self.objects.append(newObj) self.ids.append(int(newObj.getId())) dbfile.close()
def serialize(self, writer): Object.serialize(self, writer) writer(('position',) + tuple(self.position)) writer(('size',) + tuple(self.size)) writer(('rotation', self.rotation)) writer(('scale',) + tuple(self.scale)) writer(('shear',) + tuple(self.shear)) writer(('spin',) + tuple(self.spin)) if self.drivethrough == 1: writer('drivethrough') if self.shootthrough == 1: writer('shootthrough')
def define(self, aName): obj = Object() obj.nName = aName obj.pNext = None if self.symbolTable[self.nCurrentLevel] is None: self.symbolTable[self.nCurrentLevel] = obj self.symbolTableLast[self.nCurrentLevel] = obj else: objTemp = self.symbolTableLast[self.nCurrentLevel] objTemp.pNext = obj self.symbolTableLast[self.nCurrentLevel] = obj return obj
def __init__(self, detectors=None): if detectors is None: detectors = [ Detector(Object("red")), Detector(Object("blue")), Detector(Object("yellow")), Detector(Object("green")) ] self.detectors = detectors self.target = None self.frame = None self.mask = None
def loadBlenderProperties(self, object): Object.loadBlenderProperties(self, object) try: self.drive_through = object.getProperty('driveThrough').getData() except AttributeError: # No property, set default self.drive_through = 0 try: self.shoot_through = object.getProperty('shootThrough').getData() except AttributeError: # No property, set default self.shoot_through = 0
def _create_declaration(self, text): lines = text.split("\n") line = lines[0] if len(lines) > 1: text = text[text.find("\n") + 1:] else: text = "" obj = Object() obj.parse(line) if not self.is_side(obj.side): return text self.objects.append(obj) return text
def __init__(self, name = '', module_ref_name = '' ): Object.__init__( self, name ) # Electrical Stuff self.module_ref_name = module_ref_name # String self.module_ref = None # vv.Module Instance self.port_dict = {} self.param_dict = {} # Derived Electrical Stuff self.num_inputs = 0 self.num_outputs = 0
def __init__(self, filepath=None): Object.__init__(self, 0) self.filepath = filepath self.texture_number = None self.width = None self.height = None self.textureWidth = None self.textureHeight = None self.bottom_left = None self.bottom_right = None self.top_right = None self.top_left = None self.opacity = 1.0
def __init__(self, path=None): """Sets up and starts the `AppServer`. `path` is the working directory for the AppServer (directory in which AppServer is contained, by default) This method loads plugins, creates the Application object, and starts the request handling loop. """ self._running = 0 self._startTime = time.time() global globalAppServer if globalAppServer: raise ProcessRunning('More than one AppServer' ' or __init__() invoked more than once.') globalAppServer = self # Set up the import manager: self._imp = ImportManager() ConfigurableForServerSidePath.__init__(self) Object.__init__(self) if path is None: path = os.path.dirname(__file__) # os.getcwd() self._serverSidePath = os.path.abspath(path) self._webKitPath = os.path.abspath(os.path.dirname(__file__)) self._webwarePath = os.path.dirname(self._webKitPath) self.recordPID() self._verbose = self.setting('Verbose') self._plugIns = [] self._requestID = 0 self.checkForInstall() self.config() # cache the config self.printStartUpMessage() sys.setcheckinterval(self.setting('CheckInterval')) self._app = self.createApplication() self.loadPlugIns() # @@ 2003-03 ib: shouldn't this just be in a subclass's __init__? if self.isPersistent(): self._closeEvent = Event() self._closeThread = Thread(target=self.closeThread, name="CloseThread") # self._closeThread.setDaemon(1) self._closeThread.start() self._running = 1
def __init__(self): Object.__init__(self) self.SetUsesGLList(True) # properties self.sketch_ids = [0, 0, 0, 0, 0] self.values = { 'mirror': False, 'centre_straight': True, } self.color = cad.Color(128, 128, 128) self.box = None # if box is None, then the curves need reloading self.ResetCurves()
def __init__(self): Object.__init__(self) self.layer = 75 self.name = "Creature" self.__seeInvisibleAbility = False self.__handItem = None self.__clothes = {} self.AddComponent("Control") self.control = self.GetComponent("Control") self.DefineUI(self.control.ui) self.AddVerb("drop", lambda player: self.Drop())
def Init(self): global program, vao self.visualization_mode = GL_LINES vao = glGenVertexArrays(1) glBindVertexArray(vao) glClearColor(1, 1, 1, 1) self.object = Object() if len(sys.argv) > 1: image_name = sys.argv[1] else: image_name = "crater" colors, vertices = self.object.load_object(image_name) # Create vertex buffer object (vbo) vbo = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, vbo) # Copy data to VBO. glBufferData(GL_ARRAY_BUFFER, ArrayDatatype.arrayByteCount(vertices), vertices, GL_STATIC_DRAW) glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, None) glEnableVertexAttribArray(0) # Create color buffer object (CBO) cbo = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, cbo) glBufferData(GL_ARRAY_BUFFER, ArrayDatatype.arrayByteCount(colors), colors, GL_STATIC_DRAW) glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, 0, None) glEnableVertexAttribArray(1) # Load and compile shaders. self.program = ShaderProgram(vertex_shader, fragment_shader) glUseProgram(self.program.program_id) # Compute a fix transformation matrix. self.matrix = glm.mat4(1) # Scale for easier observation self.global_scale() # Bind transformation matrix. transformLoc = glGetUniformLocation(self.program.program_id, "transform") glUniformMatrix4fv(transformLoc, 1, GL_FALSE, glm.value_ptr(self.matrix)) # Enable depth test glEnable(GL_DEPTH_TEST)
def wallGenerator(self): for i in range(0, MAX_BLOCKS): for j in range(0, MAX_BLOCKS): if (i == 0) or (j == 0) or (i == MAX_BLOCKS - 1) or (j == MAX_BLOCKS - 1): temp = Object(i * 50, j * 50, "wall") #temp.toString() self.walls.append(temp) #print(self.walls) wallCount = random.randint(25, 45) print("wallcount: " + str(wallCount)) for i in range(wallCount): temp = Object(randomBlockGenerator(), randomBlockGenerator(), "wall") while self.isSameLocation(temp, self.walls): temp = Object(randomBlockGenerator(), randomBlockGenerator(), "wall") self.walls.append(temp) #print(self.walls) tempExit = Object(randomBlockGenerator(), randomBlockGenerator(), "exit") while self.isSameLocation(tempExit, self.walls): tempExit = Object(randomBlockGenerator(), randomBlockGenerator(), "wall") return tempExit.getLocation()
def __init__(self, warehouse, uid, action_topic, cmd_vel_topic, scan_topic, odom_topic, amcl_topic, vision_topic, tf_prefix, robot_description): Agent.__init__(self, warehouse, uid, action_topic) Object.__init__(self, uid, shapely.geometry.Point(tuple(robot_description['pos'])), shapely.geometry.Polygon([tuple(v) for v in robot_description['footprint']])) Vessel.__init__(self, uid) self.orientation = 0 #radian rospy.Subscriber(cmd_vel_topic, geometry_msgs.msg.Twist, self.cmd_vel_handler) self.robot_description = robot_description if scan_topic: self.scan_pub = rospy.Publisher(scan_topic, sensor_msgs.msg.LaserScan) self.scan_data = sensor_msgs.msg.LaserScan() self.scan_data.header.frame_id = tf_prefix + '/base_link' self.scan_data.angle_min = self.robot_description['laser_angle_min'] self.scan_data.angle_max = self.robot_description['laser_angle_max'] self.scan_data.angle_increment = self.robot_description['laser_angle_increment'] self.scan_data.range_min = self.robot_description['laser_range_min'] self.scan_data.range_max = self.robot_description['laser_range_max'] else: self.scan_pub = None if odom_topic: self.odom_pub = rospy.Publisher(odom_topic, nav_msgs.msg.Odometry) self.odom_broadcaster = tf.TransformBroadcaster() self.odom_data = nav_msgs.msg.Odometry() self.odom_data.header.frame_id = tf_prefix + '/odom' self.odom_data.child_frame_id = tf_prefix + '/base_link' self.init_pos = self.pos self.init_orientation = self.orientation self.init_time = rospy.Time.now() else: self.odom_pub = None if amcl_topic: self.amcl_pub = rospy.Publisher(amcl_topic, geometry_msgs.msg.PoseWithCovarianceStamped) self.amcl_data = geometry_msgs.msg.PoseWithCovarianceStamped() self.amcl_data.header.frame_id = '/map' else: self.amcl_pub = None self.vision_pub = rospy.Publisher(vision_topic, warehouse_simulator.msg.AbstractVision) for command in self.robot_description['actions'].keys(): self.add_command(command) self.add_command('vel') self.battery = Battery(self.robot_description['battery_max_quantity'], self.robot_description['battery_max_quantity'], self.robot_description['battery_recharge_rate']) self.vel = geometry_msgs.msg.Twist() self.vel_odom = geometry_msgs.msg.Twist() self.vel_target = geometry_msgs.msg.Twist() self.broken = False
def doForceTransfer(abstractGraph, optionsDict): """ Applies FTA, the node overlap prevention algorithm """ # Promote directed edges to hyperedges, useful if the edge has a large drawing # then that drawing becomes a node, and two new directed edges are created. if (optionsDict[PROMOTE_EDGE_TO_NODE] == 'Always'): abstractGraph.promoteDirectedEdge(True) elif (optionsDict[PROMOTE_EDGE_TO_NODE] == 'Smart'): abstractGraph.promoteDirectedEdge(False) # Initilize the datastructure for all objects Object.objList = [] # Build internal datastructure for nodes for abstractNode in abstractGraph.getAbstractNodeList(): #print 'abstractNode', abstractNode.getDistinctiveName() Object(abstractNode, optionsDict[MIN_NODE_DISTANCE]) # Build internal datastructure for edges if (optionsDict[MIN_LINK_DISTANCE]): for abstractEdge in abstractGraph.getAbstractEdgeList(): #print 'abstractEdge', abstractEdge, str(abstractEdge) Object(abstractEdge, optionsDict[MIN_LINK_DISTANCE]) totalNodes = len(Object.objList) # Trivial non-overlap case if (totalNodes <= 1): return # Keep at it till the layout is stable or max iterations reached i = 0 maxIterations = optionsDict[MAX_TOTAL_ITERATIONS] seperationForce = optionsDict[SEPERATION_FORCE] while (__calculationLoop(seperationForce, totalNodes) and i < maxIterations): i += 1 # Keep the whole thing in the viewable area of the canvas __forceObjectsIntoViewArea(optionsDict) # Apply the new coordinates for obj in Object.objList: obj.applyNewCoords() # All that moving stuff around can mess up the connections... __optimizeArrows(abstractGraph, optionsDict)
def test_handle_edge_collision(self): obj = Object(8, 5, 1, 1) obj.handle_edge_collision(0, 11, 0, 10) self.assertEqual(obj.x, 8, "x position should be 8") obj.update_position(2) obj.handle_edge_collision(0, 11, 0, 10) self.assertEqual(obj.x, 9, "x position should be 9")
def __str__(self): output = [Object.__str__(self)] for property in self.properties: arg = list(getattr(self, property.name)) output.append(property.pack(arg)) return "".join(output)
def __init__(self, sequence, \ id, subtype, name, \ desc, \ parent, \ contains, \ modify_time, \ *args, **kw): Object.__init__(self, sequence, id, subtype, name, desc, parent, contains, modify_time) assert subtype == self.subtype, "Type %s does not match this class %s" % (subtype, self.__class__) if len(self.properties) != len(args): raise TypeError("The args where not correct, they should be of length %s" % len(self.properties)) for property, arg in zip(self.properties, args): self.length += property.length(arg) setattr(self, property.name, arg)
def __init__(self, name ='', nettype = 'wire', msb = 0, lsb = 0 ): Object.__init__( self, name ) self.nettype = nettype self.msb = msb self.lsb = lsb self.size = 0 self.sigtype = 'normal' # or 'clock' or 'reset' - should be an enumneration self.module_ref = None self.Calc_Size()
def __init__(self, server, useSessionSweeper=1): """Called only by `AppServer`, sets up the Application.""" self._server = server self._serverSidePath = server.serverSidePath() self._imp = server._imp # the import manager ConfigurableForServerSidePath.__init__(self) Object.__init__(self) print 'Initializing Application...' print 'Current directory:', os.getcwd() if self.setting('PrintConfigAtStartUp'): self.printConfig() self.initVersions() self.initErrorPage() self._shutDownHandlers = [] # Initialize TaskManager: if self._server.isPersistent(): from TaskKit.Scheduler import Scheduler self._taskManager = Scheduler(1) self._taskManager.start() else: self._taskManager = None # Define this before initializing URLParser, so that contexts have a # chance to override this. Also be sure to define it before loading the # sessions, in case the loading of the sessions causes an exception. self._exceptionHandlerClass = ExceptionHandler self.initSessions() self.makeDirs() URLParser.initApp(self) self._rootURLParser = URLParser.ContextParser(self) self._running = 1 if useSessionSweeper: self.startSessionSweeper()
def modifyModel(field, newvalue): dest = field.split(".") nl = 0 key = None # The first element is always the nature of the object if dest[nl] == "object": key = Object.findObject(dest[nl + 1]) nl = nl + 2 elif dest[nl] == "relation": key = Object.findRelation(dest[nl + 1]) nl = nl + 2 elif dest[nl] == "library": if dest[nl + 1] == "object": key = Object.findLibObject(dest[nl + 2]) elif dest[nl + 1] == "relations": key = Object.findLibRelation(dest[nl + 2]) else: print ("There is no " + dest[nl + 1] + " field in the library!") return nl = nl + 3 else: print ("The first field name is not recognized!") return # If we want to change the parent, we will change the string "extends" if dest[nl] == "extends": key = key.parent key.parent = newvalue nl += 1 # If we want to change properties, we will change one of its properties elif dest[nl] == "properties": key = key.properties key[dest[nl + 1]] = newvalue nl = nl + 2 # If we want to change 'relations', we will change the name of the relation elif dest[nl] == "relations": key = key.relations key.remove(dest[nl + 1]) key.append(newvalue) # If we want to change 'objects', we will change the name of the object elif dest[nl] == "objects": key = key.objects key.remove(dest[nl + 1]) key.append(newvalue) else: print ("The field name is not recognized !")
def parse(fl): Object.folder = "" Object.model = False Relation.model = False model = None # open and then read the file err_str = "" war_str = "" list_obj = [] list_rel = [] with open(fl) as f: # with object_pairs_hook method, we can check "Error 07" at the same level target = json.loads(f.read()) if "library" in target.keys(): lib = "" folders = fl.split("/") for i in range(0, len(folders) - 1): lib += folders[i] + "/" lib += target["library"] # To handle all the errors and warnings in "library" json file valstr = Object.readLibrary(lib) err_str += valstr[0] war_str += valstr[1] list_obj = valstr[2] list_rel = valstr[3] # To handle all the errors and warnings in "root" json file rootobj = [] rootrel = [] valstr2 = val_root(fl, target, True, list_obj, list_rel, rootobj, rootrel) err_str += valstr2[0] war_str += valstr2[1] if err_str: print err_str else: Object.model = True Relation.model = True model = Object(fl.split(".")[0], target) Object.flatten(rootobj, rootrel) if war_str: print war_str # TO return the constructed model return model
def translate_object(self, obj, distance): obj_new = Object((0, 0), 0) obj_new.remove_pixel((0, 0)) for xy in obj.area: obj_new.add_pixel((xy[0] + distance[0], xy[1] + distance[1])) obj_new.find_centroid() return obj_new
def __init__(self, texture, frame_x = 1, frame_y = 1, clickable = False): Object.__init__(self, texture) self.position = (0, 0) self.frame_size = (1/float(frame_x), 1/float(frame_y)) self.rect = (0, 0, self.frame_size[0], self.frame_size[1]) self.pixel_size = (self.texture.pixel_size[0]/frame_x, self.texture.pixel_size[1]/frame_y) self.width, self.height = self.pixel_size self.size = (self.width, self.height) self.frames = [frame_x, frame_y] self.current_frame = (frame_x, frame_y) self.reverse_animation = False if clickable: ImageObject.clickables.append(self) self.create_arrays()
def __init__(self): self.sources = '' self.sourceList = [] self.walker = Walker() self.classes = {} self.glob = Object('<global>') self.glob.setGlobalType() classFinder = ClassFinder(self.glob, self.classes) scopeTracer = ScopeTracer() # self.walker.addWatcher(scopeTracer) self.walker.addWatcher(classFinder)
def new_game(): fighter_component = Fighter(hp=30, defense=2, power=5, xp=0, death_function=player_death) settings.player = Object(0, 0, '@', 'player', color.white, blocks=True, fighter=fighter_component) settings.player.level = 1 settings.dungeon_level = 1 make_map() handle_keys.initialize_fov() settings.game_state = 'playing' settings.inventory = [] settings.game_msgs = [] message('Welcome stranger. Prepare to perish in the ' + 'Tombs of the Ancient Kings.', color.red) equipment_component = Equipment(slot='right hand', power_bonus=2) obj = Object(0, 0, '-', 'dagger', color.sky, equipment=equipment_component) settings.inventory.append(obj) equipment_component.equip() obj.always_visible = True
def __init__(self, texture, length): Object.__init__(self, texture) self.length = length self.position = (0, 0) self.create_arrays()
def __init__(self,x,y): Object.__init__(self,x,y,POWERUP_RADIUS) self._color = (0,0,0) self._timer = 10 self._type = 'BASIC'
def __init__(self, name="Toon"): Object.__init__(self, name) self.setModel(ActorToon("neutral", False))
def __init__(self,x,y): Object.__init__(self,x,y,PLAYER_RADIUS) self._color = PLAYER_COLOR
def serialize(self, writer): Object.serialize(self, writer)
def __init__(self, diameter = 3.0, title = None, tool_number = 0, type = TOOL_TYPE_SLOTCUTTER): Object.__init__(self) self.tool_number = tool_number self.type = type self.diameter = diameter self.material = TOOL_MATERIAL_UNDEFINED self.tool_length_offset = 0.0 self.x_offset = 0.0 self.front_angle = 0.0 self.tool_angle = 0.0 self.back_angle = 0.0 self.orientation = 0 ''' // also m_corner_radius, see below, is used for turning tools and milling tools /** The next three parameters describe the cutting surfaces of the bit. The two radii go from the centre of the bit -> flat radius -> corner radius. The vertical_cutting_edge_angle is the angle between the centre line of the milling bit and the angle of the outside cutting edges. For an end-mill, this would be zero. i.e. the cutting edges are parallel to the centre line of the milling bit. For a chamfering bit, it may be something like 45 degrees. i.e. 45 degrees from the centre line which has both cutting edges at 2 * 45 = 90 degrees to each other For a ball-nose milling bit we would have - m_corner_radius = m_diameter / 2 - m_flat_radius = 0 // No middle bit at the bottom of the cutter that remains flat // before the corner radius starts. - m_vertical_cutting_edge_angle = 0 For an end-mill we would have - m_corner_radius = 0 - m_flat_radius = m_diameter / 2 - m_vertical_cutting_edge_angle = 0 For a chamfering bit we would have - m_corner_radius = 0 - m_flat_radius = 0 // sharp pointed end. This may be larger if we can't use the centre point. - m_vertical_cutting_edge_angle = 45 // degrees from centre line of tool */ ''' self.corner_radius = 0.0 self.flat_radius = 0.0 self.cutting_edge_angle = 0.0 self.cutting_edge_height = 0.0 # How far, from the bottom of the cutter, do the flutes extend? self.max_advance_per_revolution = 0.0 ''' // This is the maximum distance a tool should advance during a single // revolution. This value is often defined by the manufacturer in // terms of an advance no a per-tooth basis. This value, however, // must be expressed on a per-revolution basis. i.e. we don't want // to maintain the number of cutting teeth so a per-revolution // value is easier to use. ''' self.automatically_generate_title = True #// Set to true by default but reset to false when the user edits the title. ''' // The following coordinates relate ONLY to touch probe tools. They describe // the error the probe tool has in locating an X,Y point. These values are // added to a probed point's location to find the actual point. The values // should come from calibrating the touch probe. i.e. set machine position // to (0,0,0), drill a hole and then probe for the centre of the hole. The // coordinates found by the centre finding operation should be entered into // these values verbatim. These will represent how far off concentric the // touch probe's tip is with respect to the quil. Of course, these only // make sense if the probe's body is aligned consistently each time. I will // ASSUME this is correct. ''' self.probe_offset_x = 0.0 self.probe_offset_y = 0.0 ''' // The following properties relate to the extrusions created by a reprap style 3D printer. // using temperature, speed, and the height of the nozzle, and the nozzle size it's possible to create // many different sizes and shapes of extrusion. typedef std::pair< eExtrusionMaterial_t, wxString > ExtrusionMaterialDescription_t typedef std::vector<ExtrusionMaterialDescription_t > ExtrusionMaterialsList_t static ExtrusionMaterialsList_t GetExtrusionMaterialsList() { ExtrusionMaterialsList_t ExtrusionMaterials_list ExtrusionMaterials_list.push_back( ExtrusionMaterialDescription_t( eABS, wxString(_("ABS Plastic")) )) ExtrusionMaterials_list.push_back( ExtrusionMaterialDescription_t( ePLA, wxString(_("PLA Plastic")) )) ExtrusionMaterials_list.push_back( ExtrusionMaterialDescription_t( eHDPE, wxString(_("HDPE Plastic")) )) return(ExtrusionMaterials_list) } ''' self.extrusion_material = EXTRUSION_MATERIAL_ABS self.feedrate = 0.0 self.layer_height = 0.1 self.width_over_thickness = 1.0 self.temperature = 200 self.flowrate = 10 self.filament_diameter = 0.2 ''' // The gradient is the steepest angle at which this tool can plunge into the material. Many // tools behave better if they are slowly ramped down into the material. This gradient // specifies the steepest angle of decsent. This is expected to be a negative number indicating // the 'rise / run' ratio. Since the 'rise' will be downward, it will be negative. // By this measurement, a drill bit's straight plunge would have an infinite gradient (all rise, no run). // To cater for this, a value of zero will indicate a straight plunge. ''' self.gradient = 0.0 ''' // properties for tapping tools int m_direction // 0.. right hand tapping, 1..left hand tapping double m_pitch // in units/rev ''' if title != None: self.title = title else: self.title = self.GenerateMeaningfulName() self.ResetParametersToReasonableValues()
def serialize(self, writer): Object.serialize(self, writer) writer(('size', self.size))
def setBlenderProperties(self, object): Object.setBlenderProperties(self, object) object.addProperty('size', float(self.size), 'FLOAT') object.setName(self.name)
def __init__(self, guid): Object.__init__(self, guid)