def test_RemoteControl(self): remote_control = RemoteControl() living_room_light = Light('Living Room') kitchen_light = Light('Kitchen') stereo = Stereo('Living Room') living_room_light_on = LightOnCommand(living_room_light) living_room_light_off = LightOffCommand(living_room_light) kitchen_light_on = LightOnCommand(kitchen_light) kitchen_light_off = LightOffCommand(kitchen_light) stereo_on_with_CD = StereoOnWithCDCommand(stereo) stereo_off = StereoOffCommand(stereo) remote_control.set_command(0, living_room_light_on, living_room_light_off) remote_control.set_command(1, kitchen_light_on, kitchen_light_off) remote_control.set_command(2, stereo_on_with_CD, stereo_off) print(remote_control) remote_control.on_button_was_pushed(0) remote_control.off_button_was_pushed(0) remote_control.on_button_was_pushed(1) remote_control.off_button_was_pushed(1) remote_control.undo_button_was_pushed() remote_control.on_button_was_pushed(2) remote_control.off_button_was_pushed(2) remote_control.undo_button_was_pushed()
def resize_game_field(self, action): if action == EXPAND_FIELD_RIGHT: LevelDesign.GAME_MEASURES[0] += 32 elif action == EXPAND_FIELD_UP: LevelDesign.GAME_MEASURES[1] += 32 self.move_blocks_down() elif action == RETRACT_FIELD_LEFT: LevelDesign.GAME_MEASURES[0] -= 32 elif action == RETRACT_FIELD_DOWN: LevelDesign.GAME_MEASURES[1] -= 32 else: return self.camera = Camera(LevelDesign.GAME_MEASURES[0], LevelDesign.GAME_MEASURES[1], LevelDesign.GAME_MEASURES[2], LevelDesign.GAME_MEASURES[3]) self.settings.width = LevelDesign.GAME_MEASURES[0] self.settings.height = LevelDesign.GAME_MEASURES[1] self.set_up_boundaries() self.world = self.world[-4:] + self.world[4:-4] Light.update_surfaces(LevelDesign.GAME_MEASURES[0], LevelDesign.GAME_MEASURES[1]) for light in self.lights: light.update_obstacles(self.world) light.update_local_surfaces()
def init_level(self, level): world = "" with open(r"../Files/Levels/{0}.btmn".format(level), "r") as level_file: world = level_file.readline() self.lights = level_file.readline() self.level_settings = level_file.readline() self.swinging_lights = level_file.readline() self.level_settings = json.loads(self.level_settings, cls=Decoder) Light.set_up_surfaces(self.level_settings.width, self.level_settings.height) self.swinging_lights = json.loads(self.swinging_lights, cls=Decoder) world = json.loads(world, cls=Decoder) self.lights = json.loads(self.lights, cls=Decoder) self.level_blocks = list( filter(lambda item: isinstance(item, Block), world)) self.level_saws = list( filter(lambda item: isinstance(item, SawBlock), world)) for light in self.lights + self.swinging_lights: light.update_obstacles(self.level_blocks) self.camera = Camera(self.level_settings.width, self.level_settings.height, self.gui_settings["resolution"][0], self.gui_settings["resolution"][1]) SoundEffect.play_music(r"{0}.mp3".format(self.level_settings.music)) self.player = Player(Vector(self.level_settings.start_position), self) self.player.equipment.equip("Batarang", 3)
def post_lights(): """ Füge eine neue Lampe hinzu :body name: Name der Lampe :body ip_address: IP Adresse der Lampe :body port: Port des HTTP-Servers der Lampe """ json = request.get_json() if not json: return jsonify({'message': 'no data received'}), 400 name = json.get('name') ip_address = json.get('ip_address') port = json.get('port') if not name or not ip_address or not port: return jsonify({'message': 'information is missing'}), 400 light = Light(None, name, ip_address, port, r=json.get('r', 0), g=json.get('g', 0), b=json.get('b', 0)) light.save() return jsonify({'message': 'Light saved'}), 200
def discover_devices(self): self.lights = [] self.devices = [] responses = self.broadcast_with_resp( GetService, StateService, ) for r in responses: device = Device(r.target_addr, r.ip_addr, r.service, r.port, self.source_id, self.verbose) try: if device.is_light(): if device.supports_multizone(): device = MultiZoneLight(r.target_addr, r.ip_addr, r.service, r.port, self.source_id, self.verbose) elif device.supports_chain(): device = TileChain(r.target_addr, r.ip_addr, r.service, r.port, self.source_id, self.verbose) else: device = Light(r.target_addr, r.ip_addr, r.service, r.port, self.source_id, self.verbose) self.lights.append(device) except WorkflowException: # cheating -- it just so happens that all LIFX devices are lights right now device = Light(r.target_addr, r.ip_addr, r.service, r.port, self.source_id, self.verbose) self.lights.append(device) self.devices.append(device)
def test_casting_with_obstacles(self): block = Block((0, 0, 0), 10, 10, 10, 10) light = Light(10, 10, 50, [block]) light.update() visibitlity = light.visibility self.assertEqual(visibitlity, self.result)
def setCurrent(self): glLoadIdentity() gluLookAt(self.center[0], self.center[1], self.distance, self.center[0], self.center[1], 0, 0, 1, 0) GLState.camera = self Light.updateLights()
def handle_events(): global see_right, skeletons, items, click, bonfire_ready, background, bonfire, light, stone, wood events = get_events() for event in events: if event.type == SDL_QUIT: game_framework.quit() elif event.type == SDL_MOUSEMOTION: mousecursor.position(x=event.x, y=VIEW_HEIGHT - 1 - event.y) elif event.type == SDL_KEYDOWN and event.key == SDLK_ESCAPE: del (skeletons) del (items) del light game_framework.change_state(title_state) elif event.type == SDL_KEYDOWN and event.key == SDLK_p: game_framework.push_state(pause_state) elif event.type == SDL_MOUSEBUTTONDOWN and event.button == SDL_BUTTON_RIGHT: if collision(ui, mousecursor): if stone >= 2 and wood >= 2: game_world.remove_object(bonfire) game_world.remove_object(light) bonfire = Bonfire(player.x, player.y) game_world.add_object(bonfire, 3) bonfire.set_background(background) light = Light(bonfire.x, bonfire.y) game_world.add_object(light, 3) light.set_background(background) stone -= 2 wood -= 2 else: player.handle_event(event)
def __init__(self): # # instantiate all our classes self.comms = Comms(config.ORIGIN_NUM, config.TARGET_NUMS) self.light = Light(config.CITY_NAME, config.LATITUDE, config.LONGITUDE, config.SUNRISE_DELAY, config.SUNSET_DELAY) self.door = Door(config.REVS) self.camera = Camera(config.MAX_HORZ, config.MAX_VERT)
def setUpClass(cls): Light.set_up_surfaces(32, 32) cls.result = [(10.0, 10.0), (10.0, 10.0), (10.0, 10.0), (10.0, 10.0), (10.0, 10.0), (10.0, 10.0), (10.0, 10.0), (10.0, 10.0), (10.0, 10.0), (10.0, 10.0), (10.0, 10.0), (10.0, 10.0), (10.0, 10.0), (10.0, 10.0), (10.0, 10.0), (10.0, 10.0), (10.0, 10.0), (10.0, 10.0), (10.0, 10.0), (10.0, 10.0), (10.0, 10.0), (10.0, 10.0), (10.0, 10.0)]
def __init__(self, image_path, screen, initpos, camera): super(Player, self).__init__(image_path, screen, initpos, camera) self.speed = 5 self.base_image = pygame.transform.rotate(self.image, 180) self.flashlight = Light((0, 0, 0), self.rpos, self.rpos, 0.0, 30.0) self.headlight = Light((255, 0, 0), self.rpos, self.rpos, 0.0, 50.0) self.lights.append(self.headlight) self.lights.append(self.flashlight)
def __init__(self, *args, **kwargs): Light.__init__(self, *args, **kwargs) self.AddAttributes(Attr('Attenuation', pm.Vec3, PL.getAttenuation, PL.setAttenuation), Attr('Point', pm.Point3, PL.getPoint, PL.setPoint), Attr('Specular Color', pm.Vec4, PL.getSpecularColor, PL.setSpecularColor), parent='PointLight')
def __init__( self, *args, **kwargs ): Light.__init__( self, *args, **kwargs ) self.AddAttributes( Attr( 'Attenuation', pm.Vec3, PL.getAttenuation, PL.setAttenuation ), Attr( 'Point', pm.Point3, PL.getPoint, PL.setPoint ), Attr( 'Specular Color', pm.Vec4, PL.getSpecularColor, PL.setSpecularColor ), parent='PointLight' )
def __init__(self, device, user): from config import Config from light import Light self.config = Config(device, user) self.light = Light(device, user) # After create Light object, search for new lights. self.light.findNewLights()
def __init__(self, x, y, rope_length, obstacles=[]): """expects that set_up_surface for Light has been called""" self.x = x self.y = y self.obstacles = obstacles self.rope_length = rope_length self.bob = Pendulum(BOB_ANGLE, self.rope_length, (self.x, self.y)) self.light = Light(self.x, self.y + self.rope_length, SWINGING_LIGHT_RADIUS, self.obstacles) self.light.update()
def __init__( self, *args, **kwargs ): Light.__init__( self, *args, **kwargs ) self.AddAttributes( Attr( 'Direction', pm.Vec3, DL.getDirection, DL.setDirection ), Attr( 'Point',pm.Point3, DL.getPoint, DL.setPoint ), Attr( 'Specular Color', pm.Vec4, DL.getSpecularColor, DL.setSpecularColor ), Attr( 'Shadow Caster', bool, DL.isShadowCaster, DL.setShadowCaster ), parent='DirectionalLight' )
def __init__(self, *args, **kwargs): Light.__init__(self, *args, **kwargs) self.AddAttributes(Attr('Direction', pm.Vec3, DL.getDirection, DL.setDirection), Attr('Point', pm.Point3, DL.getPoint, DL.setPoint), Attr('Specular Color', pm.Vec4, DL.getSpecularColor, DL.setSpecularColor), Attr('Shadow Caster', bool, DL.isShadowCaster, DL.setShadowCaster), parent='DirectionalLight')
def main(): print('Reading ...') start = datetime.datetime.now() # data source name data_source_name = 'better-ball.d' # shading type: # 0 - no shading (framework) # 1 - constant shading # 2 - Gouraud shading # 3 - Phong shading shading = 3 world_space = Space() world_space.append_by_file(data_source_name + '.txt') # geometry data camera = Camera() camera.set_by_file(data_source_name + '.camera.txt') # camera profile light = Light() light.set_by_file(data_source_name + '.light.txt') # light profile material = Material() material.set_by_file(data_source_name + '.material.txt') # material profile illumination = Illumination() illumination.set(camera, light, material, shading) display = Display() display.set(800) # change window size cost = datetime.datetime.now() - start print('Finish. (cost = ' + str(cost) + ')\n') print('Calculating: transform ...') start = datetime.datetime.now() view_space = copy.deepcopy(world_space) view_space.transform(world_to_view, camera) screen_space = copy.deepcopy(view_space) screen_space.transform(view_to_screen, camera) device_space = copy.deepcopy(screen_space) device_space.transform(screen_to_device, display) cost = datetime.datetime.now() - start print('Finish. (cost = ' + str(cost) + ')\n') window = Window() window.set(world_space, device_space, illumination, display) window.show()
def test_azimut_symetry(self): azimut = 53 symetric_azimut = -azimut elevation = 10 reader = LdtReader(LDT_PATH) light = Light(reader.azimuts, reader.elevations, reader.intenzities) intenzity = light.intenzity(azimut, elevation) symetric_intenzity = light.intenzity(symetric_azimut, elevation) self.assertEqual(intenzity, symetric_intenzity)
class Bridge(): def __init__(self, device, user): from config import Config from light import Light self.config = Config(device, user) self.light = Light(device, user) # After create Light object, search for new lights. self.light.findNewLights()
def test_different(self): azimut = 53 other_azimut = 180 elevation = 10 reader = LdtReader(LDT_PATH) light = Light(reader.azimuts, reader.elevations, reader.intenzities) intenzity = light.intenzity(azimut, elevation) other_intenzity = light.intenzity(other_azimut, elevation) self.assertNotEqual(intenzity, other_intenzity)
def __init__( self, *args, **kwargs ): LensNode.__init__( self, *args, **kwargs ) Light.__init__( self, *args, **kwargs ) self.AddAttributes( Attr( 'Attenuation', pm.Vec3, SL.getAttenuation, SL.setAttenuation ), Attr( 'Exponent', float, SL.getExponent, SL.setExponent ), Attr( 'Specular Color', pm.Vec4, SL.getSpecularColor, SL.setSpecularColor ), Attr( 'Shadow Caster', bool, SL.isShadowCaster, SL.setShadowCaster ), parent='Spotlight' )
class LightTestCase(unittest.TestCase): def setUp(self): self.test_light = Light() def test_on(self): self.test_light.on() self.assertEqual(self.test_light.state,1) def test_off(self): self.test_light.off() self.assertEqual(self.test_light.state,0)
def _intenzity_matrix(azimuts: array, elevations: array) -> array: """ :return intenzity[azimut, elevation]: [lux] """ reader = LdtReader(LDT_PATH) light = Light(reader.azimuts, reader.elevations, reader.intenzities) intenzities = empty((len(azimuts), len(elevations))) for az_index, azimut in enumerate(azimuts): for el_index, elevation in enumerate(elevations): intenzity = light.intenzity(azimut, elevation) intenzities[az_index, el_index] = intenzity return intenzities
def test_casting(self): light = Light(10, 10, 50) light.update() visibitlity = light.visibility result = [(0.0, 0.00019999800003844825), (0.0, 0.0), (0.00019999800003844825, 0.0), (31.99941601284763, 0.0), (32.0, 7.105427357601002e-15), (32.0, 0.0002654533388604108), (32.0, 31.999560004399918), (32.0, 32.0), (31.999560004399914, 32.0), (0.00026545333886218714, 31.999999999999996), (7.105427357601002e-15, 32.0), (0.0, 31.999416012847632)] self.assertEqual(result, visibitlity)
class Player(Entity): def __init__(self, image_path, screen, initpos, camera): super(Player, self).__init__(image_path, screen, initpos, camera) self.speed = 5 self.base_image = pygame.transform.rotate(self.image, 180) self.flashlight = Light((0, 0, 0), self.rpos, self.rpos, 0.0, 30.0) self.headlight = Light((255, 0, 0), self.rpos, self.rpos, 0.0, 50.0) self.lights.append(self.headlight) self.lights.append(self.flashlight) def update(self, time_passed, level, currentCam): super(Player, self).update(time_passed, level, currentCam) # draw a vector between the player and the cursor # and rotate the player image to face it. # Have to use the current camera in order # to get the player's screen coordinates, (sx, sy) sx, sy = currentCam.real_to_screen(self.rpos.x, self.rpos.y) mouse_sx, mouse_sy = pygame.mouse.get_pos() mouse_rx, mouse_ry = currentCam.screen_to_real(mouse_sx, mouse_sy) dx = sx - mouse_sx dy = sy - mouse_sy player_to_mouse = Vec2d(dx, dy) self.image = pygame.transform.rotate(self.base_image, -math.degrees(player_to_mouse.angle)) # with the entity's position updated, bring the light emitter with it self.flashlight.emitter_pos = self.rpos self.flashlight.proj_pos = Vec2d(mouse_rx, mouse_ry) self.flashlight.update_surface(level) self.headlight.emitter_pos = self.rpos self.headlight.proj_pos = self.rpos self.headlight.update_surface(level) # offset the camera location to place the player # in the middle of the screen offsetX = self.rpos.x - self.camera.screen_width / 2 offsetY = self.rpos.y - self.camera.screen_height / 2 self.camera.move((offsetX, offsetY)) def movement_handler(self, keydown): self.vel.x, self.vel.y = { pygame.K_w: (self.vel.x, -1), pygame.K_s: (self.vel.x, 1), pygame.K_a: (-1, self.vel.y), pygame.K_d: (1, self.vel.y), }[keydown] self.vel = self.vel.normalized()
def __init__( self, *args, **kwargs ): kwargs['nType'] = PL Light.__init__( self, *args, **kwargs ) pAttr = Attr( 'PointLight' ) pAttr.children.extend( [ Attr( 'Attenuation', pm.Vec3, PL.getAttenuation, PL.setAttenuation ), Attr( 'Point', pm.Point3, PL.getPoint, PL.setPoint ), Attr( 'Specular Color', pm.Vec4, PL.getSpecularColor, PL.setSpecularColor ) ] ) self.attributes.append( pAttr )
def init(self): self.device = Device() self.light = Light() # self.lock = Lock() self.monitor = Monitor("localhost", 9999) # self.monitor.init() self.aliyun = Aliyun(self._queue) self.camera = Camera(self.device, self.light, self.aliyun, self.shelf_current_info, self.client_config, self.online) self._queue.put("shelf_init") self.is_init = True
def __init__( self, *args, **kwargs ): kwargs['nType'] = DL Light.__init__( self, *args, **kwargs ) pAttr = Attr( 'DirectionalLight' ) pAttr.children.extend( [ Attr( 'Direction', pm.Vec3, DL.getDirection, DL.setDirection ), Attr( 'Point',pm.Point3, DL.getPoint, DL.setPoint ), Attr( 'Specular Color', pm.Vec4, DL.getSpecularColor, DL.setSpecularColor ), Attr( 'Shadow Caster', bool, DL.isShadowCaster, DL.setShadowCaster ) ] ) self.attributes.append( pAttr )
class Recording: def __init__(self): self.CHUNK = 512 self.FORMAT = pyaudio.paInt16 self.CHANNELS = 1 self.RATE = 44100 self.RECORD_SECONDS = 3 self.WAVE_FILENAME = "output.wav" self.paudio = pyaudio.PyAudio() print self.paudio.is_format_supported(input_format=self.FORMAT, input_channels=self.CHANNELS, rate=self.RATE, input_device=2) print self.paudio.get_default_input_device_info() print self.paudio.get_device_info_by_index(2) self.led = Light(17) def record(self): self.led.set_on() stream = self.paudio.open(format=self.FORMAT, channels=self.CHANNELS, rate=self.RATE, input=True, frames_per_buffer=self.CHUNK, input_device_index=2) print("*** recording") frames = [] for i in range(0, int(self.RATE / self.CHUNK * self.RECORD_SECONDS)): data = stream.read(self.CHUNK) frames.append(data) print("*** done recording") stream.stop_stream() stream.close() self.paudio.terminate() self.led.set_off() return frames def write_to_file(self): frames = self.record() time1 = timer() wf = wave.open(self.WAVE_FILENAME, 'wb') wf.setnchannels(self.CHANNELS) wf.setsampwidth(self.paudio.get_sample_size(self.FORMAT)) wf.setframerate(self.RATE) wf.writeframes(b''.join(frames)) wf.close() time2 = timer() print 'saving time: ' + str(time2 - time1)
def __init__(self): self.CHUNK = 512 self.FORMAT = pyaudio.paInt16 self.CHANNELS = 1 self.RATE = 44100 self.RECORD_SECONDS = 3 self.WAVE_FILENAME = "output.wav" self.paudio = pyaudio.PyAudio() print self.paudio.is_format_supported(input_format=self.FORMAT, input_channels=self.CHANNELS, rate=self.RATE, input_device=2) print self.paudio.get_default_input_device_info() print self.paudio.get_device_info_by_index(2) self.led = Light(17)
def __init__( self, *args, **kwargs ): kwargs['nType'] = SL LensNode.__init__( self, *args, **kwargs ) Light.__init__( self, *args, **kwargs ) pAttr = Attr( 'PointLight' ) pAttr.children.extend( [ Attr( 'Attenuation', pm.Vec3, SL.getAttenuation, SL.setAttenuation ), Attr( 'Exponent', float, SL.getExponent, SL.setExponent ), Attr( 'Specular Color', pm.Vec4, SL.getSpecularColor, SL.setSpecularColor ), Attr( 'Shadow Caster', bool, SL.isShadowCaster, SL.setShadowCaster ) ] ) self.attributes.append( pAttr )
def __init__(self): self.world = [] self.lights = [] self.swinging_lights = [] # this is the block according to which the view will move self.observer = Block((0, 0, 0), WIDTH, HEIGHT, 0, 0) self.setup_menu_camera() self.setup_text_boxes() self.setup_buttons() self.set_up_boundaries() Light.set_up_surfaces(LevelDesign.GAME_MEASURES[0], LevelDesign.GAME_MEASURES[1]) self.settings = Settings(LevelDesign.GAME_MEASURES[0], LevelDesign.GAME_MEASURES[1], MUSIC_IN_GAME1, DEFAULT_START_POSITION)
def _decode_light(d): """ Creates a Light instance from a dictionary containing the guts of a Light instance. Parameters: d (Dictionary): The dictionary that contains the organs and ideas of the Light we are trying to coax into existence. Returns: A cultivated Light. Preconditions: The dictionary actually does specify a light. (i.e. it was encoded using _encode_light().) Postconditions: A Light is created. """ # Create the three different ColorChannels from members of the dictionary. r = ColorChannel(d['r_t'], d['r_v'], d['r_c']) g = ColorChannel(d['g_t'], d['g_v'], d['g_c']) b = ColorChannel(d['b_t'], d['b_v'], d['b_c']) # Construct and return the Light instance that wraps the ColorChannels. return Light(r, g, b, d['name'], d['id'])
def __init__(self, color=None, nickName=None, owner=None): self.wheels = [] self.light = Light() self.color = color self.nickName = nickName self.owner = owner self.direction = 0
def main(): while True: # try : ConnectDB._cursor.execute("SELECT * FROM veget") myresult = ConnectDB._cursor.fetchall() for value in myresult: print('main') veget_id = value['veget_id'] print('light work') light_result = Light.process_light(veget_id) print('fertilizer work') fertilizer_result = Light.process_fertilizer(value) print('light_result', light_result) print('fertilizer_result', fertilizer_result) sleep(60 * 10) print('this is main process from Pi')
def __init__(self, size): """Create map of size*size tiles.""" self.TILE_SIZE = 20 # pixels self.CHUNK_SIZE = 8 # blocks square self.BLOCK_UPDATE_SIZE = (40, 40) # rect size around player in blocks self.BLOCK_UPDATE_FREQ = 1000 # number of blocks to update per second self._blocks = [] # block_ids of the map in row-major order self.size = size # (width, height) of the map in blocks self.entities = [] # list of MapEntities in the map self._blocks = map_generation.generate_map(size) self._particle_systems = [] # (ParticleSystem, pos) tuples self.cursor_pos = None # pixel coords or None self.light = Light(self) # prime the chunk cache by rendering every chunk in the map self._chunk_cache = {} print "priming chunk cache..." for chunk in self.get_chunks_in_rect(((0, 0) + self.size)): s = pygame.Surface((self.CHUNK_SIZE * self.TILE_SIZE, self.CHUNK_SIZE * self.TILE_SIZE)) self.draw_chunk(s, chunk) self._chunk_cache[chunk] = s print "cached %i chunks" % len(self._chunk_cache)
def put_light(id): """ Setze den Status einer Lampe :body name (optional): Name der Lampe :body r (optional): Rotwert [0...255] :body g (optional): Grünwert [0...255] :body b (optional): Blauwert [0...255] """ json = request.get_json() if not json: return jsonify({'message': 'no data received'}), 200 light = Light.get(id) if not light: return jsonify({'message': 'Light not found'}), 404 if json.get('name') is not None: light.name = json.get('name') if json.get('r') is not None: light.r = json.get('r') if json.get('g') is not None: light.g = json.get('g') if json.get('b') is not None: light.b = json.get('b') light.save() return jsonify({'message': 'Light saved'}), 200
def __init__(self, refPath, dataPath, dbFilename): GPIO.cleanup() GPIO.setmode(GPIO.BCM) GPIO.setup(self.AUTO_START_GPIO_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP) self.__i2c = I2C(2) self.__analog = Analog(sel.__i2c.getLock(), 0x49) self.default = Default() self.database = Database(dataPath, dbFilename) self.waterlevel = Waterlevel(debug, self.database) self.light = Light(self.database) self.curtain = Curtain(self.database) self.pressure = Pressure(self.database, self.default, self.__analog) self.temperature = Temperature("28-0417716a37ff", self.database) self.redox = Redox(debug, self.database, self.default, self.__analog) self.ph = PH(debug, self.database, self.default, self.__analog, self.temperature) self.robot = Robot(debug, self.database) self.pump = Pump(debug, self.database, self.default, self.robot, self.redox, self.ph, self.temperature) self.panel = Panel(debug, self.database, self.default, self.pump, self.redox, self.ph, self.__i2c) self.statistic = Statistic(debug, self.pump, self.robot, self.redox, self.ph, self.temperature, self.pressure, self.waterlevel) self.refPath = refPath self.__autoSaveTick = 0 self.__today = date.today().day - 1 debug.TRACE(debug.DEBUG, "Initialisation done (Verbosity level: %s)\n", debug)
def main(): remote_control = RemoteControl() light = Light() light_on_command = LightOnCommand(light) light_off_command = LightOffCommand(light) fan = CellingFan() celling_fan_high_command = CellingFanHighCommand(fan) celling_fan_low_command = CellingFanLowCommand(fan) celling_fan_off_command = CellingFanOffCommand(fan) remote_control.set_command(2, light_on_command, light_off_command) remote_control.set_command(5, celling_fan_high_command, celling_fan_off_command) remote_control.set_command(6, celling_fan_low_command, celling_fan_off_command) remote_control.on_button_pushed(1) remote_control.off_button_pushed(1) remote_control.undo_button_pushed() remote_control.on_button_pushed(2) remote_control.off_button_pushed(2) remote_control.undo_button_pushed() remote_control.on_button_pushed(6) remote_control.off_button_pushed(6) remote_control.undo_button_pushed() remote_control.on_button_pushed(5) remote_control.undo_button_pushed()
def test_SimpleRemoteControl(self): remote = SimpleRemoteControl() light = Light() light_on_command = LightOnCommand(light) remote.set_command(light_on_command) remote.button_was_pressed()
def loadDb3(self, db3File, id): self.id = id self.center = db3File.queryLevelData(id, 'Center').split(',') self.extents = db3File.queryLevelData(id, 'Extents').split(',') self.startLevel = db3File.queryLevelData(id, 'StartLevel') for i in db3File.queryCategoryNames(): if i != 'Light': for j in db3File.queryEntityGuid(i, id): opObject = OpObject(id) opObject.loadDb3(db3File, j) self.opObjects.append(opObject) for i in db3File.queryEntityGuid('_Environment', id): envObject = EnvObject(id) envObject.loadDb3(db3File, i) self.envObjects.append(envObject) for i in db3File.queryEntityGuid('Light', id): light = Light(id) light.loadDb3(db3File, i) self.lights.append(light)
def init_gl(): """Initializes OpenGL settings.""" # Enable smooth shading, GL_FLAT enables flat shading glShadeModel(GL_SMOOTH) # Set the depth value to 1 when the depth buffer is cleared glClearDepth(1) # Enables depth testing, which eliminates hidden surfaces glEnable(GL_DEPTH_TEST) # Sets which function to do depth testing with # With GL_LEQUAL, any value less than or equal to the depth value in the depth buffer passes glDepthFunc(GL_LEQUAL) # Use nicest persepctive correction glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST) # Enables transparency in textures glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) Fog.init() Light.init()
def init_level(self, level): world = "" with open( r"../Files/Levels/{0}.btmn".format(level), "r") as level_file: world = level_file.readline() self.lights = level_file.readline() self.level_settings = level_file.readline() self.swinging_lights = level_file.readline() self.level_settings = json.loads(self.level_settings, cls=Decoder) Light.set_up_surfaces(self.level_settings.width, self.level_settings.height) self.swinging_lights = json.loads(self.swinging_lights, cls=Decoder) world = json.loads(world, cls=Decoder) self.lights = json.loads(self.lights, cls=Decoder) self.level_blocks = list( filter( lambda item: isinstance( item, Block), world)) self.level_saws = list( filter( lambda item: isinstance( item, SawBlock), world)) for light in self.lights + self.swinging_lights: light.update_obstacles(self.level_blocks) self.camera = Camera(self.level_settings.width, self.level_settings.height, self.gui_settings["resolution"][0], self.gui_settings["resolution"][1]) SoundEffect.play_music(r"{0}.mp3".format(self.level_settings.music)) self.player = Player(Vector(self.level_settings.start_position), self) self.player.equipment.equip("Batarang", 3)
def refresh_screen(self): if self.ingame or self.take_screenshot: self.screen.fill((255, 255, 255)) Light.nullify_shadow() Light.nullify_light() for light in self.lights: light.draw_shadow(self.camera) light.draw_light(self.camera) for swinging_light in self.swinging_lights: swinging_light.draw(self.screen, self.camera) Light.draw_everything(self.screen) for saw in self.level_saws: saw.draw(self.screen, self.camera) for block in self.level_blocks: block.draw(self.screen, self.camera) self.player.display_avatar(self.screen, self.camera) self.player.equipment.draw(self.screen, self.camera) if not self.ingame: if self.take_screenshot: self.background.blit(self.screen, (0, 0)) self.take_screenshot = False self.screen.blit(self.background, (0, 0)) Menu.MENUS[self.current_menu].draw(self.screen) pygame.display.update()
def on_draw(): """Draws output to the game window every frame.""" game_window.clear() width, height = game_window.get_size() # Sets the GL viewport with its bottom left corner at (0, 0) glViewport(0, 0, width, height) # Specify that all following operations should be on the projection matrix glMatrixMode(GL_PROJECTION) # Replace the projection matrix with the identity matrix, reseting the matrix glLoadIdentity() # Set the projection matrix gluPerspective( 70, # The field of view in degrees width / float(height), # The aspect ratio 0.1, # The closest point in z space 100 # The furthest point in z space ) # Specify that all following operations should be on the modelview matrix glMatrixMode(GL_MODELVIEW) # Replace the modelview matrix with the identity matrix, reseting the matrix glLoadIdentity() # Texture minification and magnification will use the nearest neighbor pixel, # which provides less smooth textures but is ideal for low resolution images. # Using GL_LINEAR will use linear interpolation and be visually smoother. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST) # Draw our models camera.draw() for tile in world: tile.draw() # Update lighting positions Light.update_lighting() # Update lighting positions Light.update_lighting()
def load(self): with open("../Files/Levels/level2.btmn", "r") as level: world = level.readline() light = level.readline() settings = level.readline() swinging_lights = level.readline() self.settings = json.loads(settings, cls=Decoder) LevelDesign.GAME_MEASURES[0] = self.settings.width LevelDesign.GAME_MEASURES[1] = self.settings.height Light.set_up_surfaces(LevelDesign.GAME_MEASURES[0], LevelDesign.GAME_MEASURES[1]) self.camera = Camera(LevelDesign.GAME_MEASURES[0], LevelDesign.GAME_MEASURES[1], LevelDesign.GAME_MEASURES[2], LevelDesign.GAME_MEASURES[3]) self.world = json.loads(world, cls=Decoder) self.lights = json.loads(light, cls=Decoder) self.swinging_lights = json.loads(swinging_lights, cls=Decoder) for light in self.lights + self.swinging_lights: light.update_obstacles(self.world)
def startElement(self, name, attrs): if name == 'Global': self.mangLevel.setAttributes(attrs) elif name == 'Level': self.level = Level() self.level.setAttributes(attrs) elif name == 'Objects': pass elif name == 'Object': opObject = OpObject(self.level.id) opObject.setAttributes(attrs) self.level.opObjects.append(opObject) elif name == 'Environment': pass elif name == 'EnvObject': envObject = EnvObject(self.level.id) envObject.setAttributes(attrs) self.level.envObjects.append(envObject) elif name == 'Lights': pass elif name == 'Light': light = Light(self.level.id) light.setAttributes(attrs) self.level.lights.append(light)
def draw(self, screen): screen.fill((255, 255, 255)) Light.nullify_shadow() Light.nullify_light() self.draw_light(screen) for piece in self.world: piece.draw(screen, self.camera) for swinging_light in self.swinging_lights: swinging_light.draw(screen, self.camera) Light.draw_everything(screen) self.menu.draw(screen, (0, 255, 0)) for button in self.buttons: button.draw(screen) for text_box in self.textboxes: text_box.draw(screen) self.block_textbox.draw(screen) pygame.display.update()
def main(): try: projector = Projector() except ProjectorNotConnected: no_projector_message() sys.exit(-1) light = Light() if len(sys.argv) <= 1: print "Command required." sys.exit(-1) command = sys.argv[1] time.sleep(.5) # Control light. if command == 'ON' : light.set_state(False) elif command == 'OFF' : light.set_state(True) elif command == '711': if not ENABLE_SEVLEV_EMAIL: log_to_file('711.mail.disabled\n') if light.sevlev() and ENABLE_SEVLEV_EMAIL: SEVLEV_EMAIL_INTERVAL = 5*60 # 30 minutes if int(time.time()) - get_last_email_sent_time() > SEVLEV_EMAIL_INTERVAL: log_to_file('711.mail.sending\n') send_sevlev_mail() save_last_email_sent_time() else: log_to_file('711.mail.ignoring\n') elif (command == '711-force'): send_sevlev_mail() # Control projector. if projector.is_valid_cmd(command): projector.run_cmd(command)
def __init__(self, name, adr): Light.__init__(self, name, adr)
def test_is_illuminated(self): block = Block((0, 0, 0), 10, 10, 10, 10) light = Light(5, 5, 50, [block]) light.update() self.assertTrue(light.is_illuminated([(6, 6)]))
#!/usr/bin/python import requests import json import urllib2 from light import Light import ConfigParser import datetime config = ConfigParser.RawConfigParser() config.read('hue.cfg') ip = config.get('hue', 'ip') secret = config.get('hue', 'secret') light = Light(ip, secret, 4) portland = 5746545 GMTOffset = -8 url = 'http://openweathermap.org/data/2.1/forecast/city/%s' % portland r = requests.get(url) data = json.loads(r.content) weather = [] for cast in data['list']: u = datetime.date.fromtimestamp(cast['dt'] - 60*60*GMTOffset) tomorrow = datetime.date.today() + datetime.timedelta(days=1) if(u < tomorrow): weather.append(cast['weather'][0]['main']) if('Rain' in weather): print "Set light blue for rain"
class Map: """Stores map tile data, entity positions, and draws the map. The map is made of 1.0x1.0 blocks. The map is rendered in square chunks of blocks, which are cached as surfaces to reduce the number of blits needed to draw the map. A chunk only needs to be redrawn when a block it contains is changed. """ def __init__(self, size): """Create map of size*size tiles.""" self.TILE_SIZE = 20 # pixels self.CHUNK_SIZE = 8 # blocks square self.BLOCK_UPDATE_SIZE = (40, 40) # rect size around player in blocks self.BLOCK_UPDATE_FREQ = 1000 # number of blocks to update per second self._blocks = [] # block_ids of the map in row-major order self.size = size # (width, height) of the map in blocks self.entities = [] # list of MapEntities in the map self._blocks = map_generation.generate_map(size) self._particle_systems = [] # (ParticleSystem, pos) tuples self.cursor_pos = None # pixel coords or None self.light = Light(self) # prime the chunk cache by rendering every chunk in the map self._chunk_cache = {} print "priming chunk cache..." for chunk in self.get_chunks_in_rect(((0, 0) + self.size)): s = pygame.Surface((self.CHUNK_SIZE * self.TILE_SIZE, self.CHUNK_SIZE * self.TILE_SIZE)) self.draw_chunk(s, chunk) self._chunk_cache[chunk] = s print "cached %i chunks" % len(self._chunk_cache) def get_block(self, x, y): """Return the block id at coordinates, or None if out of range.""" if (x in xrange(0, self.size[0]) and y in xrange(0, self.size[1])): i = (y * self.size[1]) + x return self._blocks[i] else: return None def set_block(self, x, y, block_id): """Set the block at coordinates to block_id. Fails if block coords are out of range. """ assert self.get_block(x, y) != None i = (y * self.size[1]) + x self._blocks[i] = block_id # invalidate the chunk cache cx = x / self.CHUNK_SIZE * self.CHUNK_SIZE cy = y / self.CHUNK_SIZE * self.CHUNK_SIZE if (cx, cy) in self._chunk_cache: del self._chunk_cache[(cx, cy)] # TODO: reuse surface? # update lighting and invalidate changed chunks # for every block with changed lighting, invalidate its chunk changed_blocks = self.light.update_light(x, y) for block in changed_blocks: cx = block[0] / self.CHUNK_SIZE * self.CHUNK_SIZE cy = block[1] / self.CHUNK_SIZE * self.CHUNK_SIZE if (cx, cy) in self._chunk_cache: del self._chunk_cache[(cx, cy)] def is_solid_block(self, x, y): """Return True if block at given coordinates is solid. Assumes blocks outside map are not solid. """ block_id = self.get_block(x, y) return (block_id != None and Block(block_id).is_solid) def draw_chunk(self, surf, pos): """Draw a self.CHUNK_SIZE square of the map tiles. surf: Surface to draw to. pos: The top-left position of the map chunk to draw. """ surf.fill((100, 100, 255)) # figure out range of tiles in this chunk tile_range = [(int(pos[i]), int(ceil(pos[i] + surf.get_size()[i] / self.TILE_SIZE))) for i in [0, 1]] for x in xrange(*(tile_range[0])): for y in xrange(*(tile_range[1])): (px, py) = self.grid_to_px(pos, (x,y)) bid = self.get_block(x, y) if bid != None: block = Block(bid) light_level = self.light.get_light(x, y) block_surf = block.lit_surfs[light_level] surf.blit(block_surf, (px, py)) else: pass #FIXME def get_chunks_in_rect(self, rect): """Generate the list of chunks inside a rect.""" x_min = rect[0] x_max = rect[0] + rect[2] y_min = rect[1] y_max = rect[1] + rect[3] chunks_x = (int(x_min) / self.CHUNK_SIZE * self.CHUNK_SIZE, int(x_max) / self.CHUNK_SIZE * self.CHUNK_SIZE) chunks_y = (int(y_min) / self.CHUNK_SIZE * self.CHUNK_SIZE, int(y_max) / self.CHUNK_SIZE * self.CHUNK_SIZE) # loop over every chunk and yield it for x in [c for c in xrange(chunks_x[0], chunks_x[1]+1) if c % self.CHUNK_SIZE == 0]: for y in [c for c in xrange(chunks_y[0], chunks_y[1]+1) if c % self.CHUNK_SIZE == 0]: yield (x, y) def draw(self, surf, pos): """Draw the map tiles and entites. surf: Surface to draw to. pos: Top-left grid position to draw. surf_size: Note: negative chunks will causing rounding in the wrong direction, causing undrawn margins. Fix this by not drawing empty chunks. """ # figure out which chunks are onscreen # get topleft and bottomright grid positions of viewport topleft = pos bottomright = self.px_to_grid(pos, surf.get_size()) # get min and max grid positions inside viewport x_min = topleft[0] x_max = bottomright[0] y_min = topleft[1] y_max = bottomright[1] # get min and max chunk positions inside viewport chunks_x = (int(x_min) / self.CHUNK_SIZE * self.CHUNK_SIZE, int(x_max) / self.CHUNK_SIZE * self.CHUNK_SIZE) chunks_y = (int(y_min) / self.CHUNK_SIZE * self.CHUNK_SIZE, int(y_max) / self.CHUNK_SIZE * self.CHUNK_SIZE) # loop over every chunk to draw for x in [c for c in xrange(chunks_x[0], chunks_x[1]+1) if c % self.CHUNK_SIZE == 0]: for y in [c for c in xrange(chunks_y[0], chunks_y[1]+1) if c % self.CHUNK_SIZE == 0]: # redraw the chunk if it's not cached if (x, y) not in self._chunk_cache: print "chunk cache miss on %i,%i" % (x, y) now = pygame.time.get_ticks() # TODO: add margin to allow tile overlapping between chunks s = pygame.Surface((self.CHUNK_SIZE * self.TILE_SIZE, self.CHUNK_SIZE * self.TILE_SIZE)) self.draw_chunk(s, (x, y)) self._chunk_cache[(x, y)] = s elapsed = pygame.time.get_ticks() - now print "cached new chunk in %i ms" % elapsed # rounding pos and blit_pos seems to fix edges between chunks blit_pos = self.grid_to_px((round(pos[0], 2), round(pos[1], 2)), (x, y)) blit_pos = (round(blit_pos[0]), round(blit_pos[1])) surf.blit(self._chunk_cache[(x, y)], blit_pos) # figure out which entities are onscreen and draw them for entity in self.entities: topleft = (entity.x, entity.y) p_tl = self.grid_to_px(pos, topleft) # TODO: clip entities offscreen entity.draw(p_tl[0], p_tl[1], entity.width * self.TILE_SIZE, entity.height * self.TILE_SIZE, surf=surf) # draw particle systems for ps_pos in self._particle_systems: (ps, g_pos) = ps_pos p_pos = self.grid_to_px(pos, g_pos) # TODO: clip ps.draw(surf, p_pos) # draw selected block if self.cursor_pos != None: selected_block = self.px_to_grid(pos, self.cursor_pos) selected_block = (int(selected_block[0]), int(selected_block[1])) rect = (self.grid_to_px(pos, selected_block) + (self.TILE_SIZE, self.TILE_SIZE)) pygame.draw.rect(surf, (255, 0, 0), rect, 2) def grid_to_px(self, topleft, pos): """Return pixel coordinate from a grid coordinate. topleft: top-left of map being drawn. pos: grid position to convert. """ return ((pos[0] - topleft[0]) * self.TILE_SIZE, (pos[1] - topleft[1]) * self.TILE_SIZE) def px_to_grid(self, topleft, pos): """Return grid coordinate from a pixel coordinate. topleft: top-left of map being drawn. pos: pixel position to convert. """ return ((float(pos[0]) / self.TILE_SIZE) + topleft[0], (float(pos[1]) / self.TILE_SIZE) + topleft[1]) def update(self, millis): """Update entities, particle systems, and blocks in the map. Blocks are updated in a rectangle around the player. Random blocks in this rectangle are chosen to be updated each call. """ for entity in self.entities: entity.update(millis, self) for ps_pos in self._particle_systems: (ps, pos) = ps_pos ps.update(millis) if ps.is_expired(): self._particle_systems.remove(ps_pos) # TODO: hack to get player pos update_center = (int(self.entities[0].x), int(self.entities[0].y)) # loop so updates occur at specified frequency for i in xrange(int(ceil(millis / float(self.BLOCK_UPDATE_FREQ * 1000)))): x = randrange(update_center[0] - self.BLOCK_UPDATE_SIZE[0]/2, update_center[0] + self.BLOCK_UPDATE_SIZE[0]/2 + 1) y = randrange(update_center[1] - self.BLOCK_UPDATE_SIZE[1]/2, update_center[1] + self.BLOCK_UPDATE_SIZE[1]/2 + 1) # update block at (x, y) bid = self.get_block(x, y) if bid == Block(name="grass").id: # kill grass which is too dark if self.light.get_light(x, y) < self.light.MAX_LIGHT_LEVEL: self.set_block(x, y, Block(name="dirt").id) # spread grass to adjacent blocks which are bright enough for pos in [(x-1,y),(x+1,y),(x,y-1),(x,y+1),(x-1,y-1), (x+1,y+1),(x-1,y+1),(x+1,y-1)]: if (self.light.get_light(*pos) == self.light.MAX_LIGHT_LEVEL and self.get_block(*pos) == Block(name="dirt").id): self.set_block(pos[0], pos[1], Block(name="grass").id) def rect_colliding(self, rect, assume_solid=None): """Return true if the given rect will collide with the map. This works by finding all the map blocks inside the rect, and returning true if any of them are solid blocks. rect should be a (x, y, w, h) tuple since pygame Rects don't use floats. If assume_solid is an (x, y) tuple, that block will be assumed solid. """ r_x = rect[0] r_y = rect[1] r_w = rect[2] r_h = rect[3] # get range of blocks inside the given rect x_range = (int(r_x), int(ceil(r_x + r_w))) y_range = (int(r_y), int(ceil(r_y + r_h))) for x in xrange(x_range[0], x_range[1]): for y in xrange(y_range[0], y_range[1]): if self.is_solid_block(x, y) or (x, y) == assume_solid: return True return False