class Renderer(): """renders a grid with values (for the gridworld)""" cell_width = 7 cell_height = 3 def __init__(self, grid): self.term = Terminal() self.grid = grid def _draw_cell(self, x, y, color, value, pos): x_mid = math.floor(self.cell_width / 2) y_mid = math.floor(self.cell_height / 2) for i in range(self.cell_width): for j in range(self.cell_height): char = ' ' print( self.term.move(y + j, x + i) + self.term.on_color(color) + '{}'.format(char) + self.term.normal) v = str(value) cx = x_mid + x cy = y_mid + y offset = len(v) // 2 if value is None: highlight = 230 elif value < 0: highlight = 1 elif value > 0: highlight = 34 # 2 else: highlight = 245 for i, char in enumerate(v): x = cx - offset + i print( self.term.move(cy, x) + self.term.on_color(color) + self.term.color(highlight) + char + self.term.normal) print( self.term.move(y, x) + self.term.on_color(color) + self.term.color(248) + '{},{}'.format(*pos) + self.term.normal) def render(self, pos=None): """renders the grid, highlighting the specified position if there is one""" print(self.term.clear()) for r, row in enumerate(self.grid): for c, val in enumerate(row): if val is None: # continue # uncomment this if holes should be nothing color = 160 else: color = 252 if (r + c) % 2 == 0 else 253 if pos is not None and pos == (r, c): color = 4 self._draw_cell(c * self.cell_width, r * self.cell_height, color, val, (r, c)) # move cursor to end print(self.term.move(len(self.grid) * self.cell_height, 0))
class Renderer(): """renders a grid with values""" cell_width = 7 cell_height = 3 def __init__(self, grid): self.term = Terminal() self.grid = grid def _draw_cell(self, x, y, color, value, pos): x_mid = math.floor(self.cell_width/2) y_mid = math.floor(self.cell_height/2) for i in range(self.cell_width): for j in range(self.cell_height): char = ' ' print(self.term.move(y+j, x+i) + self.term.on_color(color) + '{}'.format(char) + self.term.normal) v = str(value) cx = x_mid + x cy = y_mid + y offset = len(v)//2 if value < 0: highlight = 1 elif value > 0: highlight = 2 else: highlight = 245 for i, char in enumerate(v): x = cx - offset + i print(self.term.move(cy, x) + self.term.on_color(color) + self.term.color(highlight) + char + self.term.normal) print(self.term.move(y, x) + self.term.on_color(color) + self.term.color(248) + '{},{}'.format(*pos) + self.term.normal) def render(self, pos=None): """renders the grid, highlighting the specified position if there is one""" print(self.term.clear()) for r, row in enumerate(self.grid): for c, val in enumerate(row): if val is None: continue color = 252 if (r + c) % 2 == 0 else 253 if pos is not None and pos == (r, c): color = 4 self._draw_cell(c * self.cell_width, r * self.cell_height, color, val, (r,c)) # move cursor to end print(self.term.move(len(self.grid) * self.cell_height, 0))
class TerminalView: """ Terminal view to basic CLI information. """ def __init__(self): self.term = Terminal() def print_error_and_exit(self, message): """ Print an error in red and exits the program. """ sys.exit(self.term.bold_red('[ERROR] ' + message)) def print_info(self, message): """ Print an informational text. """ print(message) def text_in_color(self, message, color_code): """ Print with a beautiful color. See codes at the top of this file. """ return self.term.color(color_code) + message + self.term.normal def format_question(self, message): """ Return an info-formatted string. """ return self.term.bold(message)
def colors(): """Returns the colors in use for this terminal.""" if not hasattr(Term, "_colors"): Term._colors = {} term = Terminal() if term.color: Term._colors["text"] = term.normal if term.number_of_colors >= 256: Term._colors["name"] = term.color(35) Term._colors["url"] = term.color(45) Term._colors["hashtag"] = term.color(227) else: Term._colors["name"] = term.color(4) Term._colors["url"] = term.color(6) Term._colors["hashtag"] = term.color(3) return Term._colors
def string_color(ansi_value, string, on_color=16): term = Terminal() return term.on_color(on_color) + term.color(ansi_value) + string + term.normal
class Lores: def __init__(self): self.t = Terminal() self.height = 40 self.width = 40 self.clear() self.pixel = ' ' self._color = 0.0 self.gr_mode() def gr_mode(self): ''' moves cursor to text area :return: ''' print(self.t.move(self.height - 1)) def color(self, color: int): self._color = float(color) def plot(self, x: int, y: int): self.matrix[x,y] = self._color def hlin(self, x1: int, x2: int, y: int): ''' Equivalent of HLIN x1,x2 at y. Draws a horizontal line :param x1: :param x2: :param y: :return: ''' self.matrix[x1:x2,y] = self._color def vlin(self, y1: int, y2: int, x: int): self.matrix[x, y1:y2] = self._color def scrn(self, x: int, y: int): return int(self.matrix[x,y]) def randomize(self): ''' randomizes pixel matrix :return: ''' self.matrix = np.random.rand(self.width, self.height) * 16 def clear(self): ''' resets pixel matrix :return: ''' self.matrix = np.zeros((self.width, self.height)) def render_pixel(self, x: int, y: int, cell_color: int): with self.t.location(0,0): content = self.t.move(y, x * len(self.pixel)) content += self.t.reverse content += self.t.color(cell_color) content += self.pixel print(content, end='', flush=True) def render(self): for row_idx, row in enumerate(np.array(self.matrix)): for col_idx, cell_value in enumerate(row): cell_color = int(cell_value) self.render_pixel(col_idx, row_idx, cell_color)
import random from operator import attrgetter from typing import Iterable, Set from blessings import Terminal from conf import partitions from evolution.individual_base import Individual term = Terminal() term.grey = term.color(8) def harsh_winter(population: Set[Individual], count: int) -> Set[Individual]: # Selects `popsize` many individuals from the current population. elitist_count = int(count * 0.3) specialist_count = int(count * 0.4 / partitions) elites = select_elites(population, elitist_count) difference = population - elites specialists = select_specialists(difference, specialist_count) survivors = elites | specialists difference = population - survivors if difference: rest = set(random.sample(difference, count - len(survivors))) population = survivors | rest else: rest = set() population = survivors log_stuff(elites, rest, specialists) return population def select_elites(individuals: Iterable[Individual], count: int):
with open('all_runs.csv', 'a') as writeFile: writer = csv.writer(writeFile) writer.writerow(data) writeFile.close() print(t.bold_blue('Simulation done! Well done to our Python 🐍')) self.model_name = input( "Model name: (stash s, leave blank for default): ") if not self.model_name == 's': self.agent.model.save_weights( str(self.model_name + MODEL_EXTENSION)) print( t.bold_green('Saving model as: ') + self.model_name + MODEL_EXTENSION) else: print(t.bold_red('Model has been stashed!')) if __name__ == '__main__': t = Terminal() os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' print(t.color(213)('For f* sake!')) time.sleep(0.1) for i in range(4): UNITS = [60, 90, 120, 150] UNITS = UNITS[i] simulation = Simulation() simulation.run()
import socket import threading import sys from string import printable from blessings import Terminal import binascii t = Terminal() print(t.bold_blue_on_white('Welcome to the truly Serverless LAN Chat!')) client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) client.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) client.bind(("", 34567)) while True: data, addr = client.recvfrom(1024) with t.location(0, t.height - 1): tokens = data.decode().split() name = tokens.pop(0) ucolor = int(binascii.hexlify(name.encode()), 16) % 16 line = t.on_color(ucolor)(name) + " " + t.color(ucolor)(' '.join(tokens)) print(line)
class InteractiveViewport(CBDictInterface): """Interface for printing conversations, with intelligent formatting. """ def __init__(self, callbackdict=None): super(InteractiveViewport, self).__init__(callbackdict) self.strangers = {} self.ready = 0 # no strangers connected self.term = Terminal() sc = [self.term.color(i) for i in xrange(1, 7)] self.strangerColLabels = tuple(sc) # tweak order of colors self.strangerColors = {} def on_idSet(self, ev): tag = 'Stranger {0}'.format(len(self.strangers.keys()) + 1) self.strangers[ev.id] = tag self.write(self.formatNotification('{0} identified...'.format(tag))) def on_waiting(self, ev): output = "Waiting to connect to " + self.strangers[ev.id] self.write(self.formatNotification(output)) def on_connected(self, ev): output = "Connected to " + self.strangers[ev.id] self.write(self.formatNotification(output)) self.ready += 1 self.strangerColors[ev.id] = self.strangerColLabels[self.ready % len(self.strangerColLabels)] if self.ready == len(self.strangers.keys()): self.write('') self.ready = 0 def on_strangerDisconnected(self, ev): output = self.strangers[ev.id] + " has disconnected" self.write(self.formatNotification(output), '') # print empty string to skip a line self.strangers.clear() def on_error(self, ev): self.write(self.formatError(ev.id, ev.data)) def on_gotMessage(self, ev): self.write(self.formatMessage(ev.id, ev.data)) def on_timeout(self, ev): self.write(self.formatNotification("Idle timeout.")) self.strangers.clear() def on_messageModified(self, ev): mod_string, orig_string = self.formatCorrection(ev.old.id, ev.data, ev.old.data) self.write(mod_string, orig_string) def formatNotification(self, string): return u"{t.red}{msg}{t.normal}".format(t=self.term, msg=string) def formatMessage(self, sid, msg): """Return a string with standard Omegle message formatting. sid : str Stranger id string msg : str Message body. """ strngrName = self.strangers[sid] return u"{t.bold}{color}{strngr}: {t.normal}{msg}".format(t=self.term, color=self.strangerColors[sid], strngr=strngrName, msg=msg) def formatCorrection(self, stranger_id, mod_string, orig_string): mod_string = self.formatMessage(stranger_id, mod_string) indent = ' ' * len(self.strangers[stranger_id]) orig_string = u"{t.cyan}{0} {msg}{t.normal}".format(indent, t=self.term, msg=orig_string) return mod_string, orig_string def formatError(self, sid, err_msg): return u"{t.bold}{t.red_on_white}ERROR <{s}>: {t.normal}{t.red_on_white}{msg}{t.normal}".format(t=self.term, s=self.strangers[sid], msg=err_msg) def write(self, *args): """Print message to output. """ for msg in args: print msg
from blessings import Terminal if __name__ == "__main__": # create a new instance of Terminal class terminal = Terminal() print("Your terminal supports {0} different colors.\n".format( terminal.number_of_colors)) indentation = 3 * terminal.move_right() print("Text with different background color:") for c in range(1, terminal.number_of_colors): formatted_text = terminal.color(c)( "Sample text is displayed in different colors") print(indentation + formatted_text) print('\n') print("Text with different foreground color:") for c in range(1, terminal.number_of_colors): print(indentation + terminal.on_color(c) ("Sample text is displayed in different colors")) print('\n') # custom formatting print(terminal.bold_italic_white_on_red('Freaky text entered.')) print( terminal.bold_underline_cyan_on_black(
class TitleScreen(object): def __init__(self, name, settings_options, border_color=4, title_color=9, background_color=231, secondary_color=40, button_color=12, stale_color=22): self.t = Terminal() self.title = name self.settings_options = settings_options self.settings_active_buttons = [ option[0] for option in self.settings_options ] self.border_color = border_color self.title_color = title_color self.background_color = background_color self.secondary_color = secondary_color self.button_color = button_color self.stale_color = stale_color self.title_button_labels = ['PLAY', 'RULES', 'QUIT'] self.width = make_odd(self.t.width) self.middle_x = (self.width - 1) / 2 self.height = self.t.height - 4 with open("rules.txt", "r") as myfile: self.rulesMsg = myfile.readlines() self.border = self.t.on_color(self.background_color) + make_border( self.t, self.border_color) + self.t.normal letter_xs = [] if len(self.title) % 2 == 0: for (iletter, letter) in enumerate(self.title): x_offset = iletter - len(self.title) / 2 letter_xs.append( (self.middle_x + (x_offset * (blockletters.LETTER_WIDTH + 1) + 1), letter)) else: for (iletter, letter) in enumerate(self.title): x_offset = iletter - (len(self.title) - 1) / 2 letter_xs.append( (self.middle_x + (x_offset * (blockletters.LETTER_WIDTH + 1) - 2), letter)) self.title_y = 2 title_cursor_seq = '' for letter_tuple in letter_xs: letter_x = letter_tuple[0] letter = letter_tuple[1] true_coors = splash_coordinates(self.t, letter_x, self.title_y) letter_str = blockletters.make_letter(self.t, letter, true_coors, self.title_color) title_cursor_seq += letter_str title_cursor_seq += self.t.normal self.title_seq = title_cursor_seq print self.border print self.title_seq def make_buttons(self, labels, button_y, rowlabel=False, button_height=3, button_side_pad=4): label_y_relative = (button_height + (button_height % 2)) / 2 - 1 button_label_y = splash_coordinates(self.t, 0, button_y + label_y_relative)[1] button_separation = 6 button_label_lengths = [len(label) for label in labels] button_widths = [ button_label_len + 2 * button_side_pad for button_label_len in button_label_lengths ] button_total_width = sum(button_widths) + (len(labels) - 1) * button_separation button_left_x = self.middle_x - ((button_total_width - (button_total_width % 2)) / 2) button_label_start_xs = [] button_label_start_xs.append(button_left_x + button_side_pad) for i in range(1, len(labels)): new_x = button_label_start_xs[i - 1] + button_label_lengths[ i - 1] + 2 * button_side_pad + button_separation button_label_start_xs.append(new_x) button_x_locs = [ loc - button_side_pad for loc in button_label_start_xs ] n_buttons = len(button_x_locs) if rowlabel: n_buttons -= 1 button_cursor_seq = self.t.on_color( self.background_color) + self.t.color(self.button_color) button_cursor_seq += self.t.bold button_cursor_seq += self.t.move_x( button_label_start_xs[0] - 1) + self.t.move_y(button_label_y) button_cursor_seq += labels[0] + ':' + self.t.normal else: button_cursor_seq = '' for i in range(len(labels) - n_buttons, len(labels)): button_coors = splash_coordinates(self.t, button_x_locs[i], button_y) button_cursor_seq += rect_string(self.t, button_coors, button_widths[i], button_height, self.button_color, fill=True) button_cursor_seq += self.t.on_color(self.button_color) + self.t.color( self.secondary_color) for i in range(len(labels) - n_buttons, len(labels)): button_cursor_seq += self.t.move_x(button_label_start_xs[i]) button_cursor_seq += self.t.move_y(button_label_y) button_cursor_seq += labels[i] button_cursor_seq += self.t.normal + self.t.move(self.t.height - 2, 0) buttons = button_cursor_seq blinker_y = button_y - 1 blinker_x_locs = [x - 2 for x in button_x_locs] blinker_widths = [width + 4 for width in button_widths] blinker_height = button_height + 2 blinker_strings = [] stale_blinker_strings = [] blinker_ender_strings = [] for i in range(len(labels) - n_buttons, len(labels)): blinker_coords = splash_coordinates(self.t, blinker_x_locs[i], blinker_y) blinker_str = rect_string(self.t, blinker_coords, blinker_widths[i], blinker_height, self.secondary_color, fill=False) stale_blinker_str = rect_string(self.t, blinker_coords, blinker_widths[i], blinker_height, self.stale_color, fill=False) blinker_ender_str = rect_string(self.t, blinker_coords, blinker_widths[i], blinker_height, self.background_color, fill=False) blinker_strings.append(blinker_str) stale_blinker_strings.append(stale_blinker_str) blinker_ender_strings.append(blinker_ender_str) blinkers = blinker_strings stale_blinkers = stale_blinker_strings blinker_enders = blinker_ender_strings return buttons, blinkers, stale_blinkers, blinker_enders def update_datetime(self): datetime_padding = 5 hr = datetime.datetime.fromtimestamp(time.time()).strftime('%I') minute = datetime.datetime.fromtimestamp( time.time()).strftime(':%M %p') self.timestr = hr.lstrip('0') + minute time_cursor_seq = '' x_time, y_time = splash_coordinates(self.t, datetime_padding, self.height - 2) time_cursor_seq += self.t.move_x(x_time) + self.t.move_y(y_time) time_cursor_seq += self.t.on_color( self.background_color) + self.t.color(self.secondary_color) time_cursor_seq += self.t.bold + self.timestr + self.t.normal self.time = time_cursor_seq weekday = datetime.datetime.fromtimestamp( time.time()).strftime('%A, %B ') daynum = datetime.datetime.fromtimestamp( time.time()).strftime('%d, %Y') self.datestr = weekday + daynum.lstrip('0') date_cursor_seq = '' x_date, y_date = splash_coordinates( self.t, self.width - len(self.datestr) - datetime_padding, self.height - 2) date_cursor_seq += self.t.move_x(x_date) + self.t.move_y(y_date) date_cursor_seq += self.t.on_color( self.background_color) + self.t.color(self.secondary_color) date_cursor_seq += self.t.bold + self.datestr + self.t.normal self.date = date_cursor_seq print self.date print self.time def print_copyright(self): cr_msg = 'Made by Jonah Majumder on July 28, 2016.' len_cr = len(cr_msg) x_null, y_cr = splash_coordinates(self.t, 0, self.height - 10) x_cr = self.middle_x - (len_cr - (len_cr % 2)) / 2 cr_cursor_seq = self.t.move_y(y_cr) + self.t.move_x(x_cr) cr_cursor_seq += self.t.on_color(self.background_color) + self.t.color( self.secondary_color) cr_cursor_seq += self.t.bold + cr_msg + self.t.normal print cr_cursor_seq def do_buttons(self, button_labels, button_y, functions, start_cols, rowlabels, button_height, button_side_pad): rows = len(button_labels) buttons = '' blinkers = [] stale_blinkers = [] blinker_enders = [] active_cols = [] for i in range(rows): button_row, blinker_row, stale_blinker_row, blinker_ender_row = self.make_buttons( button_labels[i], button_y[i], rowlabels[i], button_height[i], button_side_pad[i]) buttons += button_row blinkers.append(blinker_row) stale_blinkers.append(stale_blinker_row) blinker_enders.append(blinker_ender_row) active_cols.append(start_cols[i]) print buttons active_row = rows - 1 for irow in range(rows): if irow == active_row: print blinkers[irow][active_cols[irow]] else: print stale_blinkers[irow][active_cols[irow]] print self.t.move(self.t.height - 2, 0) try: while True: char = getch() if char == 'w': if active_row > 0: print stale_blinkers[active_row][ active_cols[active_row]] print blinkers[active_row - 1][active_cols[active_row - 1]] print self.t.move(self.t.height - 2, 0) active_row -= 1 elif char == 's': if active_row < rows - 1: print stale_blinkers[active_row][ active_cols[active_row]] print blinkers[active_row + 1][active_cols[active_row + 1]] print self.t.move(self.t.height - 2, 0) active_row += 1 elif char == 'a': if active_cols[active_row] > 0: print blinker_enders[active_row][ active_cols[active_row]] print blinkers[active_row][active_cols[active_row] - 1] print self.t.move(self.t.height - 2, 0) active_cols[active_row] -= 1 elif char == 'd': if active_cols[active_row] < len(blinkers[active_row]) - 1: print blinker_enders[active_row][ active_cols[active_row]] print blinkers[active_row][active_cols[active_row] + 1] print self.t.move(self.t.height - 2, 0) active_cols[active_row] += 1 elif char == u'\n': if active_row == rows - 1: break else: print stale_blinkers[active_row][ active_cols[active_row]] print blinkers[active_row + 1][active_cols[active_row + 1]] print self.t.move(self.t.height - 2, 0) active_row += 1 else: pass except KeyboardInterrupt: self.clean_exit() functions(active_cols) def title_function(self, active_cols): title_fns = [self.advance_to_settings, self.rules, self.clean_exit] title_fns[active_cols[len(active_cols) - 1]]() def do_title_buttons(self, start_button): title_rowlabel = False start_button -= title_rowlabel self.do_buttons([self.title_button_labels], [self.title_y + 9], self.title_function, [start_button], [title_rowlabel], [3], [4]) def do_settings_buttons(self, settings_options): settings_button_labels = [] y_locs = [] rowlabels = [] start_buttons = [] button_heights = [] button_paddings = [] for s in range(len(settings_options)): option = settings_options[s] rowlabels.append(option[0]) y_locs.append(2 if s == 0 else y_locs[s - 1] + button_heights[s - 1] + 3) settings_button_labels.append(option[1]) button_heights.append(option[2][0]) button_paddings.append(option[2][1]) self.do_buttons(settings_button_labels, y_locs, self.process_settings, self.settings_active_buttons, rowlabels, button_heights, button_paddings) def process_settings(self, active_cols): self.settings_active_buttons = active_cols action_index = active_cols[len(active_cols) - 1] if action_index == 0: self.back_to_title('PLAY') elif action_index == 1: settings_dict = {} for iSetting, setting in enumerate(self.settings_options): if setting[0]: settings_dict[setting[1][0]] = setting[1][ setting[0] + active_cols[iSetting]] self.settings = settings_dict self.advance_to_game() else: raise Exception( 'Setting screen action index was not 0 or 1! How did that happen?!' ) def show_content(self): print self.title_seq self.update_datetime() self.print_copyright() def advance_to_settings(self): self.redraw_border() self.do_settings_buttons(self.settings_options) def advance_to_game(self): # self.redraw_border() # msg = str(self.settings) # with self.t.location(self.middle_x - ((len(msg) - (len(msg)%2))/2), 8): # print self.t.bold + msg + self.t.normal # while True: # char = getch() # if char == u'\n': # break pass def redraw_border(self): with self.t.location(): print make_clearer_string(self.t) with self.t.location(0, 1): print self.border def back_to_title(self, title_button): self.redraw_border() self.show_content() self.do_title_buttons(self.title_button_labels.index(title_button)) def rules(self): self.redraw_border() rulemsg = self.rulesMsg for (iLine, line) in enumerate(rulemsg): with self.t.location( self.middle_x - ((len(line) - (len(line) % 2)) / 2), 4 + iLine): print self.t.bold + line + self.t.normal while True: char = getch() if char == u'\n': break self.back_to_title('RULES') def clean_exit(self): with self.t.location(): print make_clearer_string(self.t) msg = 'Thanks for playing ' + self.title + '!' with self.t.location(self.middle_x - ((len(msg) - (len(msg) % 2)) / 2), 8): print self.t.bold + msg + self.t.normal sys.exit() def start(self): self.update_datetime() self.print_copyright() self.do_title_buttons(self.title_button_labels.index('PLAY'))