def __init__(self, strip, stop, lock): super(Game, self).__init__(strip, stop, lock) self.board = [' '] * 9 self.player_name = '' self.player_marker = '' self.bot_name = 'TBot' self.bot_marker = '' self.winning_combos = ( [6, 7, 8], [3, 4, 5], [0, 1, 2], [0, 5, 6], [1, 4, 7], [2, 3, 8], [0, 4, 8], [2, 4, 6], ) self.corners = [0, 2, 6, 8] self.sides = [1, 3, 5, 7] self.middle = 4 self.form = ''' \t| %s | %s | %s | \t------------- \t| %s | %s | %s | \t------------- \t| %s | %s | %s | ''' self.bot_color = Color.random_color() self.player_color = Color.random_color(ignore=self.bot_color) LOG.debug("TicTacToe init")
def print_error_info(e): print( Color.control( 'During the code execution, error has occurred. Please try again or contact the support.' )) print(Color.error('Message: \'{}\'.').format(str(e)) + '\n') print(traceback.format_exc())
def testCheckeredPigment(self): color1 = Color(1.0, 2.0, 3.0) color2 = Color(10.0, 20.0, 30.0) pigment = CheckeredPigment(color1=color1, color2=color2, num_of_steps=2) # With num_of_steps == 2, the pattern should be the following: # # (0.5, 0) # (0, 0) +------+------+ (1, 0) # | | | # | col1 | col2 | # | | | # (0, 0.5) +------+------+ (1, 0.5) # | | | # | col2 | col1 | # | | | # (0, 1) +------+------+ (1, 1) # (0.5, 1) assert pigment.get_color(Vec2d(0.25, 0.25)).is_close(color1) assert pigment.get_color(Vec2d(0.75, 0.25)).is_close(color2) assert pigment.get_color(Vec2d(0.25, 0.75)).is_close(color2) assert pigment.get_color(Vec2d(0.75, 0.75)).is_close(color1)
def test_parsing(self): p = Polygon.parse({ 'points': [[1, 2], [0, 9]], 'color': "#332211" }, {}, Color("#990011")) self.assertEqual(p.points, [(1, 2), (0, 9)]) self.assertEqual(p.color, Color("#332211"))
def testFurnace(self): pcg = PCG() # Run the furnace test several times using random values for the emitted radiance and reflectance for i in range(5): world = World() emitted_radiance = pcg.random_float() reflectance = pcg.random_float( ) * 0.9 # Be sure to pick a reflectance that's not too close to 1 enclosure_material = Material( brdf=DiffuseBRDF( pigment=UniformPigment(Color(1.0, 1.0, 1.0) * reflectance)), emitted_radiance=UniformPigment( Color(1.0, 1.0, 1.0) * emitted_radiance), ) world.add_shape(Sphere(material=enclosure_material)) path_tracer = PathTracer(pcg=pcg, num_of_rays=1, world=world, max_depth=100, russian_roulette_limit=101) ray = Ray(origin=Point(0, 0, 0), dir=Vec(1, 0, 0)) color = path_tracer(ray) expected = emitted_radiance / (1.0 - reflectance) assert pytest.approx(expected, 1e-3) == color.r assert pytest.approx(expected, 1e-3) == color.g assert pytest.approx(expected, 1e-3) == color.b
def test_parse(self): p = Square.parse({'x': 1, 'y': 2, 'size': 3}, {}, Color("#123456")) self.assertEqual(p.x, 1) self.assertEqual(p.y, 2) self.assertEqual(p.width, 3) self.assertEqual(p.height, 3) self.assertEqual(p.color, Color("#123456"))
def test_average_luminosity(self): img = HdrImage(2, 1) img.set_pixel(0, 0, Color(0.5e1, 1.0e1, 1.5e1)) img.set_pixel(1, 0, Color(0.5e3, 1.0e3, 1.5e3)) assert pytest.approx(100.0) == img.average_luminosity(delta=0.0)
def __init__(self, engine=None, scheduler=None, options=None): if options: self.size = Vector(*[int(_) for _ in options.size.split('x')]) self.width = self.size[0] self.height = self.size[1] self.num_frames = options.num_frames self.fps = options.fps self.background = Color(options.background) self.foreground = Color(options.foreground) self.grid = options.grid else: self.width = defaults.WIDTH self.height = defaults.HEIGHT self.size = Vector(self.width, self.height) self.num_frames = defaults.NUM_FRAMES self.fps = defaults.FPS self.background = Color(defaults.BACKGROUND) self.foreground = Color(defaults.FOREGROUND) self.grid = defaults.GRID self.engine = engine if engine else PyGameEngine( width=self.width, height=self.height, fps=self.fps) self.engine.fg_color = self.foreground self.engine.bgcolor = self.background self.scheduler = scheduler if scheduler else Scheduler() self.actors = [] self.refs = { 'center': self.size / 2, 'top_right': Vector(self.width, 0), 'top_left': Vector(0, 0), 'bottom_right': Vector(self.width, self.height), 'bottom_left': Vector(0, self.height), }
def print_limits_info(limits_data, limit_type): info_container = { 'query': { 'title': 'API query limits for used API Key', 'available': 'Webservice API usage limits: {}', 'used': 'Current API usage: {}', }, 'submission': { 'title': 'Submission limits for used API Key', 'available': 'Submission limits: {}', 'used': 'Used submission limits: {}', }, 'quick_scan': { 'title': 'Quick scan submission limits for used API Key', 'available': 'Submission limits: {}', 'used': 'Used submission limits: {}', }, } formatted_limits = CliLimitsFormatter.format(limits_data, limit_type) texts = info_container[limit_type] if formatted_limits: print(Color.control(texts['title'])) print(texts['available'].format(formatted_limits['available'])) print(texts['used'].format(formatted_limits['used'])) print('Is limit reached: {}'.format( Color.success('No') if formatted_limits['limit_reached'] is False else Color.error('Yes')))
def __init__(self, dbg): self.ins_history = [] # TODO: Keep history of registers? Can get memory intensive? self.dbg = dbg self.commands_dict = { # Change funcion pointers to Command objects with description 'exit': self.stop, 'quit': self.stop, 'help': self.print_help, 'registers': self.print_diff, 'memory': self.print_memory, 'clear': self.clear_screen, 'history': self.print_history, 'zero': self.zero_registers, # Add command to pass a string to radare? } self.before_regs = dbg.get_registers() self.after_regs = self.before_regs self.retdec = Retdec() if Context().debug_enabled: self.commands_dict.update({ 'debug': self.debug, }) self.running = True signal.signal(signal.SIGINT, self.int_handler) Color.print(Color.RED, 'Initialized shell')
def print_register_diff(self, a, b): for k, v in b.items(): if a[k] != v: print(k + ': ', end='') Color.print(Color.BLUE, str(v)) else: print(k + ': ' + str(v))
def set_model(command): userid = int(command[1]) model = str(command[2]) if model == '0': inthandle = _remove_model(userid) if inthandle is not None: Player.from_userid(userid).color = Color(255, 255, 255, 255) return _remove_model(userid) if 'models/' not in model: model = 'models/' + model player = Player.from_userid(userid) player.color = Color(255, 255, 255, 0) model = Model(model) entity = Entity.create('prop_dynamic_override') entity.origin = player.origin entity.parent = player entity.set_model(model) entity.spawn() _game_models[entity.inthandle] = player.userid entity.add_output('OnUser1 !self,Kill,,0,1')
def _on_player_pre_attack(self, attacker, victim, **kwargs): if randint(1, 100) > 20 or self.cooldowns['blizzard'] > 0 or self.level == 0: return self._center = victim.origin self._player = attacker self._players_hit.clear() self._repeater = Repeat(self._repeat) self._repeater.start(0.1) self._effect = TempEntity('BeamRingPoint', center=self._center, start_radius=self.range, end_radius=self.range+1, model_index=self._model.index, halo_index=self._model.index, life_time=7, amplitude=10, red=200, green=200, blue=255, alpha=245, flags=0, start_width=10, end_width=10) self._effect.create() self._stack = Entity.create('env_smokestack') self._stack.teleport(self._center, QAngle(0, 180, 0), None) self._stack.base_spread = self.range / 2 self._stack.spread_speed = 10 self._stack.start_size = 2 self._stack.end_size = 1 self._stack.jet_length = 100 self._stack.angles = QAngle(0, 0, 0) self._stack.rate = 600 self._stack.speed = 100 self._stack.twist = 180 self._stack.render_mode = RenderMode.TRANS_COLOR self._stack.render_amt = 100 self._stack.render_color = Color(200, 200, 255) self._stack.add_output('SmokeMaterial particle/rain.vmt') self._stack.turn_on() self._stack2 = Entity.create('env_smokestack') self._stack2.teleport(self._center, None, QAngle(0, 180, 0)) self._stack2.base_spread = self.range / 4 self._stack2.spread_speed = self.range / 2 self._stack2.start_size = 2 self._stack2.end_size = 1 self._stack2.jet_length = 100 self._stack2.angles = QAngle(0, 180, 0) self._stack2.rate = 600 self._stack2.speed = 100 self._stack2.twist = 120 self._stack2.render_mode = RenderMode.TRANS_COLOR self._stack2.render_amt = 100 self._stack2.render_color = Color(200, 200, 255) self._stack2.add_output('SmokeMaterial particle/rain.vmt') self._stack2.turn_on() send_wcs_saytext_by_index(self._msg_a.format(name=victim.name), attacker.index) self._stack.delay(7, self._stack.turn_off) self._stack2.delay(7, self._stack2.turn_off) Delay(7, self._repeater.stop) self.cooldowns['blizzard'] = 10
def get_colored_prepared_response_msg(self): response_msg = self.api_object.get_prepared_response_msg() response_msg_success_nature = self.api_object.get_response_msg_success_nature( ) return Color.success( response_msg ) if response_msg_success_nature is True else Color.error(response_msg)
def test_normalize_image(self): img = HdrImage(2, 1) img.set_pixel(0, 0, Color(0.5e1, 1.0e1, 1.5e1)) img.set_pixel(1, 0, Color(0.5e3, 1.0e3, 1.5e3)) img.normalize_image(factor=1000.0, luminosity=100.0) assert img.get_pixel(0, 0).is_close(Color(0.5e2, 1.0e2, 1.5e2)) assert img.get_pixel(1, 0).is_close(Color(0.5e4, 1.0e4, 1.5e4))
def test_parse(self): p = Point.parse({ 'x': 10, 'y': 2, 'color': '(255, 0, 255)' }, {}, Color("#990011")) self.assertEqual(p.x, 10) self.assertEqual(p.y, 2) self.assertEqual(p.color, Color("#ff00ff"))
def test_diffrent_color_place(self): p = Point.parse({ 'x': 10, 'y': 2, 'color': 'cos' }, {'cos': "#123456"}, Color("#990011")) self.assertEqual(p.color, Color("#123456")) p = Point.parse({'x': 10, 'y': 2}, {'cos': "123456"}, Color("#123456")) self.assertEqual(p.color, Color("#123456"))
def draw_fill(ctx, color=Color(1, 1, 1,1)): ctx.save() if isinstance(color, Color): ctx.set_source_rgba(*color.get_array()) elif isinstance(color, str): ctx.set_source_rgba(*Color.from_html(color).get_array()) elif isinstance(color, cairo.Pattern): ctx.set_source(color) ctx.fill() ctx.restore()
def run(self): LOG.debug("Starting Helloween2") LOG.debug("Stip length : {}".format(self.strip.length)) crange = [ Color().AQUAMARINE, Color().BROWN, Color().CYAN, Color().DARKVIOLET, Color().RED, Color().DARKGREEN, Color().DARKBLUE, Color().YELLOW ] while not self.stop.is_set(): pumkin = random.choice(self.pumpkins) color = random.choice(crange[:-1]) for _ in '0110010110110011010101110111': self.lock.acquire() if _ == random.choice(['0', '1']): for pixel in pumkin: pixel.set_color(color=Color().BLACK) else: for pixel in pumkin: pixel.set_color(color=color) self.strip.show() self.lock.release() time.sleep(0.05) time.sleep(random.randint(2, 5) * 0.5) LOG.debug("Helloween2 Mode Stopped") self.strip.all_off()
def run(self): LOG.debug("Starting Firelane") crange = [ Color().AQUAMARINE, Color().BROWN, Color().CYAN, Color().DARKVIOLET, Color().RED, Color().DARKGREEN, Color().DARKBLUE, Color().YELLOW ] round = 0 pcol = random.choice(crange) while not self.stop.is_set(): round += 1 if round == 51: round = 1 pcol = random.choice(crange) for p in range(self.strip.length): if p == round: self.strip.set_pixel(p, color=Color().BLACK) else: self.strip.set_pixel(p, color=pcol) self.strip.show() LOG.debug("Firelane Stopped") self.strip.all_off()
def draw_stroke(ctx, line_width, color=Color(0,0,0,1)): ctx.save() if isinstance(color, Color): ctx.set_source_rgba(*color.get_array()) elif isinstance(color, str): ctx.set_source_rgba(*Color.from_html(color).get_array()) else: ctx.set_source(color) ctx.set_line_width(line_width) ctx.stroke() ctx.restore()
def Color(self): color = Color(); value = 0; if self.la.kind == 2: value = self.Percentage() color.modify("percentage", value); self.BaseColor(color) elif self.StartOf(1): self.BaseColor(color) else: self.SynErr(30) return color
def test_clamp_image(self): img = HdrImage(2, 1) img.set_pixel(0, 0, Color(0.5e1, 1.0e1, 1.5e1)) img.set_pixel(1, 0, Color(0.5e3, 1.0e3, 1.5e3)) img.clamp_image() for cur_pixel in img.pixels: assert (cur_pixel.r >= 0) and (cur_pixel.r <= 1) assert (cur_pixel.g >= 0) and (cur_pixel.g <= 1) assert (cur_pixel.b >= 0) and (cur_pixel.b <= 1)
def test_diffrent_color_place(self): p = Polygon.parse({'points': [[1, 2]]}, {}, Color("#332211")) self.assertEqual(p.points, [(1, 2)]) self.assertEqual(p.color, Color("#332211")) p = Polygon.parse( { 'points': [[1, 2], [2, 3], [2, 3]], 'color': 'magenta' }, {'magenta': '(255, 0, 255)'}, Color("#332211")) self.assertEqual(p.points, [(1, 2), (2, 3), (2, 3)]) self.assertEqual(p.color, Color("#ff00ff"))
def test_parse(self): p = Rectangle.parse({ 'x': 1, 'y': 2, 'height': 2, 'width': 3 }, {}, Color("#123456")) self.assertEqual(p.x, 1) self.assertEqual(p.y, 2) self.assertEqual(p.height, 2) self.assertEqual(p.width, 3) self.assertEqual(p.color, Color("#123456"))
def test_errors(self): with self.assertRaises(ValueError): Polygon.parse({'point': [[1, 2]]}, {}, Color("#332211")) Polygon.parse({ 'points': [[1, 2], [0, 9]], 'color': "#3321" }, {}, Color("#990011")) Polygon.parse({ 'points': [[1, 2], [0, 9]], 'color': "#332211" }, {}, Color("#11")) with self.assertRaises(TypeError): Polygon.parse({'points': (1)}, {}, Color("#332211"))
def test_operations(self): col1 = Color(1.0, 2.0, 3.0) col2 = Color(5.0, 7.0, 9.0) assert (col1 + col2).is_close(Color(6.0, 9.0, 12.0)) assert (col1 - col2).is_close(Color(-4.0, -5.0, -6.0)) assert (col1 * col2).is_close(Color(5.0, 14.0, 27.0)) prod_col = Color(1.0, 2.0, 3.0) * 2.0 assert prod_col.is_close(Color(2.0, 4.0, 6.0))
def give_trail(ent, team): if team == 2: color = Color(255, 0, 0) if team == 3: color = Color(0, 0, 255) entity = TempEntity('BeamFollow') entity.start_width = 3 entity.end_width = 3 entity.color = color entity.model = beam_model entity.halo = beam_model entity.entity_index = ent.index entity.life_time = 2 entity.create()
def print_banner(bootstrap, no_shell_file): """Print the Pigweed or project-specific banner""" enable_colors() print(Color.green('\n WELCOME TO...')) print(Color.magenta(_PIGWEED_BANNER)) if bootstrap: print( Color.green('\n BOOTSTRAP! Bootstrap may take a few minutes; ' 'please be patient')) print( Color.green( ' On Windows, this stage is extremely slow (~10 minutes).\n')) else: print( Color.green( '\n ACTIVATOR! This sets your console environment variables.\n' )) if no_shell_file: print(Color.bold_red('Error!\n')) print( Color.red(' Your Pigweed environment does not seem to be' ' configured.')) print(Color.red(' Run bootstrap.bat to perform initial setup.')) return 0
def test_errors(self): with self.assertRaises(ValueError): Rectangle.parse({ 'y': 2, 'height': 2, 'width': 3 }, {}, Color("#123456")) Rectangle.parse({ 'x': 1, 'height': 2, 'width': 3 }, {}, Color("#123456")) Rectangle.parse({'x': 1, 'y': 2, 'width': 3}, {}, Color("#123456")) Rectangle.parse({ 'x': 1, 'y': 2, 'height': 2 }, {}, Color("#123456")) Rectangle.parse({'x': 1, 'y': 2, 'height': 2, 'width': 3}, {}, 1) with self.assertRaises(TypeError): Rectangle.parse({ 'x': {}, 'y': 2, 'height': 2, 'width': 3 }, {}, Color("#123456")) Rectangle.parse( { 'x': 1, 'y': (), 'height': 1, 'width': 3, 'color': "(0, 255, 0)" }, {}, Color("#123456")) Rectangle.parse( { 'x': 1, 'y': 2, 'height': [], 'width': 3, 'color': "(0, 255, 0)" }, {}, Color("#123456")) Rectangle.parse( { 'x': 1, 'y': 2, 'height': 2, 'width': "", 'color': "(0, 255, 0)" }, {}, Color("#123456")) Rectangle.parse( { 'x': 1, 'y': 2, 'height': 2, 'width': 3, 'color': "(0, 255, 0)" }, {}, 1)
def update(self): colors = { 'white': Color(255, 255, 255), 'black': Color(0, 0, 0), 'red': Color(255, 0, 0), 'green': Color(0, 255, 0), 'blue': Color(0, 0, 255) } for r in range(len(self.__tracked)): for c in range(len(self.__tracked[0])): color = self.__mapping[self.__tracked[r][c]] if color in colors: color = colors[color] self.__grid[Point(c, r)] = color self.__gui.render()
def test_palette_has_index(self): palette = Palette(a=Color.from_hex("#FF0000")) index = palette._tree self.assertTrue(index is not None) # def test_rebuild_changes_index(self): # palette = Palette() # palette["a"] = (1, 2) # # index = palette.distance_index # palette["b"] = (2, 4) # # self.assertNotEquals(palette.distance_index, index)
def output(self, level = 0): if level == 0: ll = self.get_list() self.len_name = 10 + max(len(os.path.basename(n['name'])) for n in ll) self.set_len_name(self.len_name) color = Color(not self.settings['nocolor']) if self.settings['view'] == 'list': l = self.get_list() h_line = '|' + ('=' * (35)) + '|' style = '| {0:13} | {1:7} | {2:7} |' if len(l) > 0: l = sorted(l, key=operator.itemgetter(self.settings['sort'])) len_name = max(len(n['name']) for n in l) len_size = max(max(len(str(n['size'])) for n in l), 11) h_line = '|' + ('=' * (len_name + len_size + 19)) + '|' style = '| {0:' + str(len_name) + '} | {1!s:>11} | {2!s:>' + str(len_size) + '} |' print (h_line) print (style.format('name', 'lines', 'size')) print (h_line) for f in l: print (style.format(f['name'], str(f['line']), str(f['size']))) print (h_line) elif self.settings['view'] == 'tree': self.sort(self.settings) shift = ' ' * level if level == 0: print ('\n' + self.name) for d in self.list_folders: msg = shift + color.green() + '+- ' + color.blue() + os.path.basename(d.name) + color.end() if self.settings['folder'] == 'local': (n, files, dirs, lines, size ) = d.get() msg += ' ({0} files, {1} folders, {2} lines, {3})'.format(files, dirs, str(lines), str(size)) if self.settings['folder'] == 'global': (n, files, dirs, lines, size ) = d.get_g() msg += ' ({0} files, {1} folders, {2} lines, {3})'.format(files, dirs, str(lines), str(size)) if self.settings['folder'] == 'both': (n1, f1, d1, l1, s1 ) = d.get() (n2, f2, d2, l2, s2 ) = d.get_g() msg += ' ({0} + {1} = {2} files, {3} + {4} = {5} folders, {6} + {7} = {8} lines, {9} + {10} = {11})'.format(f1, f2, f1 + f2, d1, d2, d1 + d2, str(l1), str(l2), str(l1 + l2), str(s1), str(s2), str(s1 + s2)) print (msg) d.output(level+1) if len(self.list_files) > 0 and self.settings['hide_files'] == False: for f in self.list_files: msg = '{0:' + str(self.len_name) + '} ({1:>8} lines, {2:>10})' + color.end() print (msg.format(shift + color.green() + '+-' + color.end() + os.path.basename(f.name) + color.gray(), str(f.line), str(f.size))) ### stats if level == 0: if self.settings['stats'] in ['short', 'all']: (n, f, d, l, s) = self.total() print ('\nstatistics:') print ('\tfolders : '+ str(d)) print ('\tfiles : '+ str(f)) print ('\tlines : '+ str(l)) print ('\tsize : '+ str(s)) if self.settings['stats'] == 'all': le = self.get_dict() print ('\nby extention:') for e in le: print ("{0!s:>8}".format(e['ext']) + ' : ' + "{0!s:>10}".format(str(e['files'])) + ' files; ' + "{0!s:>12}".format(str(e['lines'])) + ' lines ' + "{0!s:>12}".format(str(e['size'])))
def setColor(self): self.__color = random.choice(Color.getColors())
def test_nearest_web_almost_white(self): palette = Palette(**WEB_PALETTE) almost_white = Color.from_hex("#FFFFFe") white = Color.from_hex("#FFFFFF") self.assertEquals(palette.find_nearest(almost_white)[0], "white") self.assertEquals(palette.find_nearest(almost_white)[1], white)
def test_nearest_web_red(self): palette = Palette(**WEB_PALETTE) red = Color.from_hex("#FF0000") self.assertEquals(palette.find_nearest(red)[0], "red") self.assertEquals(palette.find_nearest(red)[1], red)