class Signature(HasTraits): color = String(desc='color signature name') dimmest = Color(desc='dimmest allowable RGB intensities') brightest = Color(desc='brightest allowable RGB intensities') def __eq__(self, other): return self.dimmest == other.dimmest or self.brightest == other.brightest def __ne__(self, other): return self.dimmest != other.dimmest and self.brightest != other.brightest def __hash__(self): return hash( (hash(self.dimmest), hash(self.brightest)) ) # color signature is all that matters for identification purposes def __setattr__(self, attribute, setting): if attribute == 'dimmest' and hasattr(self, 'brightest'): assert self.brightest != setting, '{} `dimmest` and `brightest` attributes are equal ({})'.format( self.__class__.__name__, setting) elif attribute == 'brightest' and hasattr(self, 'dimmest'): assert self.dimmest != setting, '{} `dimmest` and `brightest` attributes are equal ({})'.format( self.__class__.__name__, setting) HasTraits.__setattr__(self, attribute, setting) def __str__(self): return '{}(color:{}, dimmest:{}, brightest:{})'.format( self.__class__.__name__, self.color, self.dimmest, self.brightest)
def fetch_user_friends(username, limit=30): friends_dict = {} page = 1 # make a request to get friends info method = "user.getFriends" params = {'user': username, 'limit': limit} while 1: params['page'] = page print Color.emphasise('--- user=%s friends page=%d ---' % (username, page)) result = api_request(method, params=params) if result is not None and 'friends' in result: obj = result['friends'] else: return None if page == 1 and 'user' not in obj: # no friends return friends_dict else: attr = obj['@attr'] last_page = int(attr['totalPages']) if isinstance(obj['user'], dict): u = obj['user'] friends_dict[u['name']] = u else: for u in obj['user']: friends_dict[u['name']] = u page += 1 if page > last_page: # just return the result return friends_dict
def main(): color = Color() draw_picture() cli_args = parse_args() # parse CLI for arguments try: i_pwned = HIBPApi(passwd=cli_args.password, file_passwd=cli_args.file_passwd) i_pwned.make_request_to_hibp() except KeyboardInterrupt: print(color.brush('\ninterrupted by user. Shutting down', 'purple')) sys.exit()
def update_db(self, alist, delete=False): filtered_list = [] for record in alist: track_id = self.filter_record(record) if track_id is not None: for target in build_revert_relation()[self.username]: target_id = build_targets_hash()[target] filtered_list.append((target_id, track_id)) if filtered_list: print "--- %s %d records to db ---" % (Color.ok("update") ,len(filtered_list)) if FriendHistory.debug is False: FriendHistory.db.executemany( "update friend_listeners set FriendsListenerNum = FriendsListenerNum + 1 where target_id == ? and track_id == ?;", filtered_list) if FriendHistory.debug is True: # do not actually touch db return if delete: FriendHistory.db.execute("delete from meta_info where friend = ?", (self.username,)) else: if alist: last_timestamp = alist[-1]["date"]["uts"] FriendHistory.db.execute( "update meta_info set timestamp = ? where friend = ?", (last_timestamp, self.username)) FriendHistory.db.commit()
def log_this(self, page): params = {"limit": self.per_page, "page": page, 'extend': 1} params.update(self.params) print "--- %s ---" % Color.fail("error request") if self.debug is False: print >> History.logf, request_url(self.method, params) History.logf.flush()
def log_this(self, page): params = {"limit": FriendHistory.per_page, "page": page, 'extend': 1} params.update(self.params) if FriendHistory.debug is True: # write to screen print "--- %s ---" % Color.fail("error request") print >> FriendHistory.log_file, request_url(self.METHOD, params) FriendHistory.log_file.flush()
def update_friends(username, index, all_): friends_dict = fetch_user_friends(username) if friends_dict is not None and len(friends_dict) != 0: # for friend, info in friends_dict.iteritems(): # if friend not in all_friends: # tags = get_user_tags(friend) # all_friends[friend] = transfer_friend_info(info,tags) # taste = get_tasteometer(username, friend) # friends_of_targets[username].append((friend, taste[0], taste[1])) func = partial(nameless, username) obj = BatchRegulate(func, friends_dict.items(), cap=20) sum_ = len(friends_dict) count = 1 for i in obj: print Color.ok("-------user=%s(%d/%d) friend=(%d/%d)------" % ( username, index, all_, count, sum_)) count += 1 else: friends_of_targets[username] = []
def blink(self, delay=0.25, num_blinks=4): backup = self._array for i in range(num_blinks): self._array = [[Color(0, 0, 0) for i in range(self._height)] for j in range(self._width)] self.display() time.sleep(delay) self._array = backup self.display() time.sleep(delay)
def get_user_tags(username): tags = [] method = "user.getTopTags" params = {'user': username} result = api_request(method, params=params) if result is None: print Color.fail("----failed to get tags for %s----" % username) elif 'toptags' in result: result = result['toptags'] if 'tag' in result: elem = result['tag'] if isinstance(elem, list): for tag in elem: tags.append((tag['name'], int(tag['count']))) else: # single dict tags.append((elem['name'], int(elem['count']))) else: # no tags print Color.emphasise("---- %s have no tags----" % username) return tags
def mutate(self): # Randomly choose the amount of mutation to be done. mutation_size = max(1, int(round(random.gauss(15, 4)))) // 100 # Randomly choose the mutation type from PARAMS. # Options --> diameter, pos, color mutation_type = random.choice(Gene.PARAMS) if mutation_type == "diameter": self._diameter = max( 1, random.randint(int(self._diameter * (1 - mutation_size)), int(self._diameter * (1 + mutation_size)))) elif mutation_type == "pos": x = max( 0, random.randint(int(self._pos.x * (1 - mutation_size)), int(self._pos.x * (1 + mutation_size)))) y = max( 0, random.randint(int(self._pos.y * (1 - mutation_size)), int(self._pos.y * (1 + mutation_size)))) self._pos = Point(min(x, self._width), min(y, self._height)) # mutation_type == color else: r = min( max( 0, random.randint(int(self._color.r * (1 - mutation_size)), int(self._color.r * (1 + mutation_size)))), 255) g = min( max( 0, random.randint(int(self._color.g * (1 - mutation_size)), int(self._color.g * (1 + mutation_size)))), 255) b = min( max( 0, random.randint(int(self._color.b * (1 - mutation_size)), int(self._color.b * (1 + mutation_size)))), 255) alpha = min( max( 0, random.randint( int(self._color.alpha * (1 - mutation_size)), int(self._color.alpha * (1 + mutation_size)))), 255) self._color = Color(r, g, b, alpha)
def create(_self_, target, settings): name = target.split( ' <:> ' )[1] # [Section] name suffix (after <:>) assumed to be the machine name on local network width = settings.getint(target, 'width') height = settings.getint(target, 'height') port = settings.getint(target, 'port') color = settings.get(target, 'color') dimmest = settings.get(target, 'dimmest') brightest = settings.get(target, 'brightest') dimmest = Color(**dict( zip(('Red', 'Green', 'Blue'), [int(this) for this in dimmest.split(',')]))) brightest = Color(**dict( zip(('Red', 'Green', 'Blue'), [int(this) for this in brightest.split(',')]))) assert brightest != dimmest, '{} `dimmest` and `brightest` attributes are equal ({})'.format( self.__name__, dimmest) signature = _self_.Signature(color=color, brightest=brightest, dimmest=dimmest) monitor = _self_.Monitor(width=width, height=height) log = logging.getLogger(name) parameters = dict( zip(('name', 'color', 'signature', 'monitor', 'port', 'log'), (name, color, signature, monitor, port, log))) return _self_(**parameters)
def __init__(self, size): # Let diameter of circle be randomly from [2, 15) self._diameter = random.randint(2, 15) self._size = size self._width, self._height = self._size # Randomly choose a pixel point in the image space. self._pos = Point(random.randint(0, self._width), random.randint(0, self._height)) # Randomly assign color to pixel with random opacity self._color = Color(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
def get_tasteometer(user1, user2): artists = [] method = 'tasteometer.compare' params = {'type1': 'user', 'type2': 'user', 'value1': user1, 'value2': user2, 'limit': 10} result = api_request(method, params=params) score = 0.0 if result is None: print Color.fail("----failed to compare %s and %s----" % (user1, user2)) elif 'comparison' in result and 'result' in result['comparison']: result = result['comparison']['result'] score = float(result['score']) arts = result['artists'] if 'artist' in arts: elem = arts['artist'] if isinstance(elem, list): for art in elem: artists.append(art['name']) else: # single dict artists.append(elem['name']) else: #no common artist print Color.emphasise("---- %s and %s have common artist ----" % (user1, user2)) return (score, artists)
def update_db(self, alist, target=None): if self.debug == True: return print "--- %s %d records to db ---" % (Color.ok("update") ,len(alist)) History.cursor.executemany(self.insert_sql, map(self.convert_recent_info, alist)) if target is None: History.cursor.execute("delete from meta_info where name = ?", (self.username,)) else: History.cursor.execute( "update meta_info set target = ? where name = ?", (target, self.username)) History.conn.commit()
def __init__(self, log, colors, options, args): logging.basicConfig(filename=log, level=logging.DEBUG, filemode='w') Color.init(colors) self.background = Color.by_html('c6cfbf') if len(args) > 0: self.world = World.load_json(args[0]) self.cols = self.world.cols self.rows = self.world.rows self.density = int(100.0 * len(self.world._objects) / (self.cols * self.rows)) else: self.cols = options.cols self.rows = options.rows self.density = options.density self.world = self.create_world() self.is_force = False self.size = (self.cols * Window.CELL_SIZE, self.rows * Window.CELL_SIZE) self.scale = float(min(Window.SIZE)) / max(self.size) self.position = [Window.SIZE[0]/2, Window.SIZE[0]/2] # set up pygame pygame.init() pygame.display.set_caption('Life') self.clock = pygame.time.Clock() # set up the window self.surface = pygame.display.set_mode(Window.SIZE, 0, 32) self.world_surface = pygame.Surface(self.size) # set up fonts self.font = pygame.font.SysFont(None, 16) self.font_color = Color.by_name('white') self.downpos = None
def lines(state: State, place: Place) -> Tuple[str, str]: """ For given member place, get the tf status line strings (two lines per member) <player name> <hp>/<hpmax> <hpdiff to max> <player state> <ep> <sp>/<spmax> <* if player is cast target> For example: Ruska 408/ 445 -37 ldr 224 1404/1404 :param member: member data :returns: Tuple of two strings for tf status lines """ if place not in state.places: return (" ", " ") member = state.places[place] name = colorize("{0: >9}".format(member.name[:8]), nameColor(member)) hp = colorize( "{0: >4}".format(member.hp), greenRedGradient(member.hp, member.maxhp, 200, 0.2), ) maxhp = "{0: >4}".format(member.maxhp) hpdiff = colorize( "{0: >5}".format(member.hp - member.maxhp or ""), Color(0xEA, 0x22, 0x22) ) memberStateTuple = getMemberState(member) memberState = colorize("{0: >5}".format(memberStateTuple[0]), memberStateTuple[1]) memberIsTarget = ( colorize("{0:4}".format("*"), YELLOW) if state.target == member.name else " " ) return ( "{0} {1}/{2}{3}".format( name, hp, maxhp, hpdiff, ), "{0} {1: >3} {2: >4}/{3: >4} {4}".format( memberState, member.ep if member.ep is not None else "?", member.sp if member.sp is not None else "?", member.maxsp if member.maxsp is not None else "?", memberIsTarget, ), )
def create (_self_, target, settings): name = target.split(' <:> ')[1] # [Section] name suffix (after <:>) assumed to be the machine name on local network width = settings.getint (target, 'width') height = settings.getint (target, 'height') port = settings.getint (target, 'port') color = settings.get (target, 'color') dimmest = settings.get (target, 'dimmest') brightest = settings.get (target, 'brightest') dimmest = Color (**dict (zip (('Red','Green','Blue'), [int(this) for this in dimmest .split(',')]))) brightest = Color (**dict (zip (('Red','Green','Blue'), [int(this) for this in brightest.split(',')]))) assert brightest != dimmest, '{} `dimmest` and `brightest` attributes are equal ({})'.format(self.__name__,dimmest) signature = _self_.Signature (color=color, brightest=brightest, dimmest=dimmest) monitor = _self_.Monitor (width=width, height=height) log = logging.getLogger (name) parameters = dict (zip (('name','color','signature','monitor','port','log'),(name,color,signature,monitor,port,log))) return _self_ (**parameters)
def greenRedGradient( n: int, n_max: int, all_red_abs: int, all_red_ratio: float ) -> Color: all_red = max(all_red_abs, int(n_max * all_red_ratio + 0.5)) if n < all_red: return RED if n >= n_max: return GREEN # http://stackoverflow.com/a/340245 # green is 0 and red 1, so invert the ratio to get maximum to be green # also, bottom 10% is already handled, so reduce 10% of maximum from both n_ratio = 1 - ((n - all_red) / (n_max - all_red)) r = int(255 * n_ratio + 0.5) g = int(255 * (1 - n_ratio) + 0.5) return Color(r, g, 0)
def _initFrames(self): if self.curvature is not None: cmin, cmax = 0., 0. for frame, cont in self.curvature.items(): for _, C in cont: if np.max(C) > cmax: cmax = np.max(C) if np.min(C) < cmin: cmin = np.min(C) color = Color(scaleMin=cmin, scaleMax=cmax) frames = list() for frame in range(1,len(self.data)+1): # Plot the localisations kernel, Z, Xgrid, Ygrid, extent = self.data[frame] # This is the contour.kdfEstimate im = plt.imshow(np.exp(Z), extent=extent, origin='lower', cmap=plt.cm.Greys_r) artists = [im, ] if self.plotContour: contourPaths = list() ax = im.get_axes() # get the image axes if self.curvature is not None: # for frame, cont in self.curvature.items(): for contour, C in self.curvature[frame]: XY = contour.vertices cColor = [ color(i) for i in C ] contourPaths.append( ax.scatter(x=XY[:,0], y=XY[:,1], c=cColor, alpha=self.alpha, edgecolor='none', s=self.s, cmap=plt.cm.seismic_r) ) elif self.contour is not None: for path in self.contour[frame]: XY = path.vertices contourPaths.append( ax.scatter(x=XY[:,0], y=XY[:,1], c='red', alpha=self.alpha, edgecolor='none', s=self.s, cmap=plt.cm.seismic_r) ) else: print("Cannot plot the contour. It is not (yet) available?") # Add the artists to the frame artists.extend(contourPaths) frames.append( artists ) return frames
def draw(self, screen): """ 绘制 """ topLeft = ((Settings.initialWindowSize[0] - self._restartImageDay.get_width()) / 2, (Settings.initialWindowSize[1] - self._restartImageDay.get_height()) / 2) screen.blit( self._restartImageNight if self._game.showNightImage() else self._restartImageDay, topLeft) color = Color.invert( Color.dimGray) if self._game.showNightImage() else Color.dimGray gameoverImage = pygame.font.Font(Settings.courierNewBoldFontPath, 48).render('G A M E O V E R', True, color) topLeft = ( (Settings.initialWindowSize[0] - gameoverImage.get_width()) / 2, topLeft[1] - gameoverImage.get_height() * 2) screen.blit(gameoverImage, topLeft)
def visualize_seam_on_image(pixels, seam_xs): """ Draws a red line on the image along the given seam. This is done to visualize where the seam is. This is NOT one of the functions you have to implement. """ h = len(pixels) w = len(pixels[0]) new_pixels = [[p for p in row] for row in pixels] for y, seam_x in enumerate(seam_xs): min_x = max(seam_x - 2, 0) max_x = min(seam_x + 2, w - 1) for x in range(min_x, max_x + 1): new_pixels[y][x] = Color(255, 0, 0) return new_pixels
def __init__(self, width=20, height=32, pin=18, freq_hz=800000, dma=5, invert=False, brightness=50): # 1D LED strip self._strip = rpi_ws281x.PixelStrip(width * height, pin, freq_hz, dma, invert, brightness) self._strip.begin() self._width = width self._height = height # Color data for each pixel, in list-of-lists format self._array = [[Color(0, 0, 0) for i in range(height)] for j in range(width)] #Index as _array[row][col] # List to use for indexing into led strip (vectorization) self._indices = [i for i in range(width * height)]
def visualize_seam_end_on_image(pixels, end_x): """ Draws a red box at the bottom of the image at the specified x-coordinate. This is done to visualize approximately where a vertical seam ends. This is NOT one of the functions you have to implement. """ h = len(pixels) w = len(pixels[0]) new_pixels = [[p for p in row] for row in pixels] min_x = max(end_x - 5, 0) max_x = min(end_x + 5, w - 1) min_y = max(h - 11, 0) max_y = h - 1 for y in range(min_y, max_y + 1): for x in range(min_x, max_x + 1): new_pixels[y][x] = Color(255, 0, 0) return new_pixels
def showSrcInfo(self, target_inst_races): db = SrcInfoDB() fd = open(self.fpath_.replace('.race', '.race-summary'), 'w') print '========= %70s =========\n' % Color.green(self.fpath_) fd.write('========= %70s =========\n' % Color.green(self.fpath_)) run_races = self.loadRuntimeRace(target_inst_races) for inst_race in target_inst_races: src_info_1 = db.lookup(inst_race.first_inst_id_) src_info_2 = db.lookup(inst_race.second_inst_id_) race_str = '%s %s X %s %s' % ( inst_race.first_inst_id_, src_info_1, inst_race.second_inst_id_, src_info_2) seperator_str = '=' * 90 print '\n'.join([seperator_str, race_str, seperator_str]) if len(run_races[inst_race]) < 10: for run_race in run_races[inst_race]: print run_race else: print len(run_races[inst_race]), print 'File:', self.fpath_.replace('.race', '.race-summary') print Color.pink('-' * 90), '\n' fd.writelines([seperator_str, race_str, seperator_str]) for run_race in run_races[inst_race]: fd.write(str(run_race)) fd.write('\n') fd.write(Color.pink('-' * 90) + '\n') print Color.blue(seperator_str), '\n' db.close() fd.close()
def pattern_at(self, pattern, point): return Color(point.x, point.y, point.z)
def pattern_at(self, pattern, point): c1 = pattern.a.pattern_at(pattern.a, point) c2 = pattern.b.pattern_at(pattern.b, point) c3 = Color.add(c1, c2) return Color(c3.r/2, c3.g/2, c3.b/2)
def turnOff(self): self._array = [[Color(0, 0, 0) for i in range(self._height)] for j in range(self._width)] self.display()
class HIBPApi(object): color = Color() uri = 'https://api.pwnedpasswords.com/range/' headers = {'user_agent': 'pass_pwned'} def __init__(self, passwd, file_passwd): self.passwd = passwd self.path = file_passwd def passwd_check(self, attempts=3): """ Check single password in HIBP database using web-API (sleeping between request to prevent HTTP 429 (Rate limit exceeded), please refer to https://haveibeenpwned.com/API/v2) :param attempts: number of attempts to check :return: result of the check as string """ try: print('[{}] Checking password in DB:'.format( self.color.brush('working', 'cyan'))) encrypted_pass = PassEncrypt(self.passwd).encrypt() for attempt in range(attempts): hibp_request = requests.get('{}{}'.format( self.uri, encrypted_pass[:5]), headers=self.headers) if hibp_request.status_code == 200: raw_data = hibp_request.text.split('\n') suffixes = { hash_suff.split(':')[0]: int(hash_suff.split(':')[1].replace('\r', '')) for hash_suff in raw_data } breaches = suffixes.get(encrypted_pass[5:].upper()) if breaches is not None: return self.color.brush( 'Your password is PWNeD (appears {} times in DB) :(' .format(breaches), 'red') return self.color.brush( 'Your password is not found in HIBP DB', 'green') time.sleep(1.5) print('{}'.format( self.color.brush('Unexpected response code. Shutting down', 'purple'))) sys.exit() except Exception as e: print('[{}] oops, something went wrong: {}'.format( self.color.brush('fail', 'red'), e)) print('{}'.format( self.color.brush('Exception raised. Shutting down', 'purple'))) sys.exit() def file_check(self, attempts=3): """ Check set of passwords provided from the file in HIBP database using web-API (sleeping between request to prevent HTTP 429 (Rate limit exceeded), please refer to https://haveibeenpwned.com/API/v2) :param attempts: number of attempts to check :return: dictionary with password as key and result of the check as value """ file_passwd = extract_passwd(self.path) pass_dict = {} completion = 0 start_time = time.time() num_of_passwd = len(file_passwd) print('[{}] Checking passwords in HIBP DB:'.format( self.color.brush('working', 'cyan'))) try: for passwd in file_passwd: progress_bar(completion, num_of_passwd, start_time) encrypted_pass = PassEncrypt(passwd).encrypt() for attempt in range(attempts): hibp_request = requests.get('{}{}'.format( self.uri, encrypted_pass[:5]), headers=self.headers) if hibp_request.status_code == 200: raw_data = hibp_request.text.split('\n') suffixes = { hash_suff.split(':')[0]: int(hash_suff.split(':')[1].replace('\r', '')) for hash_suff in raw_data } breaches = suffixes.get(encrypted_pass[5:].upper()) if breaches is not None: pass_dict[ passwd] = 'PWNeD (appears {} times in DB) :('.format( breaches) break pass_dict[passwd] = 'Not found in HIBP DB' break time.sleep(1.5) pass_dict.setdefault(passwd, 'Not able to check') time.sleep(1.5) completion += 1 progress_bar(completion, num_of_passwd, start_time) return pass_dict except Exception as e: print('[{}] oops, something went wrong: {}'.format( self.color.brush('fail', 'red'), e)) print('{}'.format( self.color.brush('Exception raised. Shutting down', 'purple'))) sys.exit() def make_request_to_hibp(self): """ Make single request to HIBP or several requests, depends CLI arguments provided (single password or file with passwords) """ if self.passwd is not None: checked_passwd = self.passwd_check() print(checked_passwd) print('[{}] for more information visit: {}'.format( self.color.brush('done', 'green'), self.color.brush('haveibeenpwned.com', 'purple'))) else: write_pass_to_file(self.file_check()) print('For more information visit: {}'.format( self.color.brush('haveibeenpwned.com', 'red')))
def __init__(self, *args, **kwargs): super(Predator, self).__init__(*args, **kwargs) self.base_health = 100 self.current_health = self.base_health self.color = Color.by_name('OrangeRed')
Floor.material.pattern = CheckerPattern() Floor.material.reflection = 0.4 Floor.material.ambient = 0.8 Floor.material.diffuse = 0.2 Floor.material.specular = 0.2 _sphere = Sphere() _sphere.transform = translation(0, 1, -0.5) _sphere.material = Material() _sphere.material.diffuse = 0.1 _sphere.material.shininess = 200.0 _sphere.material.transparency = 0 _sphere.material.reflective = 0.6 _sphere.material.refractive_index = 1.52 _sphere.material.ambient = 0.6 _sphere.material.color = Color(1, 0, 0) _sphere.material.specular = 0.6 _sphere2 = Sphere() _sphere2.transform = np.matmul(translation(1.7, 0.7, -0.9), scaling(0.7, 0.7, 0.7)) _sphere2.material = Material() _sphere2.material.diffuse = 0.4 _sphere2.material.shininess = 200.0 _sphere2.material.transparency = 0 _sphere2.material.reflective = 0.2 _sphere2.material.refractive_index = 1.52 _sphere2.material.ambient = 0.8 _sphere2.material.color = Color(0.1, 0.3, 1) _sphere2.material.specular = 0.8 # glassSphere.transform = scaling(0.5, 0.5, 0.5)
SpellBind, SpellBinds, SpellsForCategory, State, ) from spells import ( DamType, getDamtypeColor, Spell, ) from utils import Color, colorize SOCKET_FILE = "/var/run/user/{0}/bcproxy-tf-scripts-caster".format(getuid()) YELLOW = Color(0xFF, 0xFF, 0) def draw(s): print("\033c", end="") # clear screen print(s) def categoryBindHelp(category: Category, categoryBinds: CategoryBinds) -> str: getCatStr: Callable[[CategoryBind], str] = ( lambda cb: colorize(cb.explanation, YELLOW) if cb.category == category else cb.explanation ) return "\n".join(map(lambda cbs: " ".join(map(getCatStr, cbs)), categoryBinds))
def getDamtypeColor(damType: Optional[DamType]) -> Optional[Color]: if damType == DamType.ACID: return Color(0, 255, 0) # green elif damType == DamType.ASPHYXIATION: return Color(202, 31, 123) # magenta elif damType == DamType.COLD: return Color(0, 0, 255) # blue elif damType == DamType.ELECTRICITY: return Color(125, 249, 255) # electric blue elif damType == DamType.FIRE: return Color(226, 88, 34) # flame elif damType == DamType.MAGICAL: return Color(255, 130, 67) # mango tango elif damType == DamType.POISON: return Color(46, 139, 87) # sea green elif damType == DamType.PSI: return Color(10, 186, 181) # tiffany blue elif damType == DamType.HARM: return Color(139, 133, 137) # taupe gray elif damType == DamType.PHYSICAL: return Color(192, 192, 192) # silver elif damType == DamType.HEAL: return Color(253, 245, 230) # old lace else: return None
from __future__ import print_function import sys import os sys.path.insert(0,'/home/pi/pixelcanvas') import numpy from random import randint from random import choice import copy from utils import Color BLANK = Color(000, 000, 000) # empty space CYAN = Color(000, 255, 255) #long piece BLUE = Color(000, 000, 255) #backwards L ORANGE = Color(255, 150, 000) #normal L YELLOW = Color(255, 255, 000) #square GREEN = Color(000, 128, 000) #backwards z PURPLE = Color(128, 000, 128) #t RED = Color(255, 000, 000) #normal z COLORS = [BLANK, CYAN, BLUE, ORANGE, YELLOW, GREEN, PURPLE, RED] UP = 0 LEFT = 1 DOWN = 2 RIGHT = 3 MOVLEFT = 0 MOVRIGHT = 1
def __init__(self, primary=Color.white(), secondary=Color(), transform_matrix=identity): super().__init__(primary, secondary, transform_matrix)
import dill # type: ignore from multiprocessing.connection import Listener from os import getuid from typing import cast, NamedTuple, Optional, Tuple from partytypes import Member, Place, State from utils import Color, colorize SOCKET_FILE = "/var/run/user/{0}/bcproxy-tf-scripts-party".format(getuid()) RED = Color(0xFF, 0, 0) GREEN = Color(0, 0xFF, 0) YELLOW = Color(0xFF, 0xFF, 0) WHITE = Color(0xFF, 0xFF, 0xFF) OUT_OF_FORMATION_COLOR = Color(204, 153, 255) def draw(s): print("\033c", end="") # clear screen print(s) def getMemberState(member: Member) -> Tuple[str, Optional[Color]]: """ String and color for member state """ # ambushed is missing as batmud gives that in pss but not in the party # status message for batclient if member.unconscious == 1: return ("unc", RED)
def __init__(self, *args, **kwargs): super(Plant, self).__init__(*args, **kwargs) self.base_health = 100 self.current_health = self.base_health self.color = Color.by_name('YellowGreen')