def main(): """ Main function """ record = GameRecord(ARGS.filename) game_list = record[:] game_label_list = [game.label for game in game_list] while True: int_response = Cli.list_menu(Enumeration(game_label_list)) move_list = game_list[int_response - 1][:] print Enumeration(move_list) goban = Goban(game_list[int_response - 1].header_dict['SZ']) color = 'black' for move in move_list: Cli.wait() Cli.clear() print goban goban.place_stone(move.address[0], move.address[1], color) if color == 'black': color = 'white' elif color == 'white': color = 'black'
def main(): """ This particular file shows a point oscillating left and right along the x-axis. """ goban = Goban(size=SIZE_, sh_obj=Cli(), adjust_ssize=-8) current_frame_no = 0 while True: for i in range(-(goban.max_domain), goban.max_domain + 1, int(round(D_INTERVAL))): goban.fill('empty') goban.plot_point(i, 0, 'white') current_frame_no += 1 Cli.print_header('+f{}'.format(current_frame_no)) print((str(goban).rstrip())) # pylint: disable=C0325 time.sleep(T_INTERVAL) for i in range(-(goban.max_domain - 1), (goban.max_domain), int(round(D_INTERVAL))): goban.fill('empty') goban.plot_point(-i, 0, 'black') current_frame_no += 1 Cli.print_header('+f{}'.format(current_frame_no)) print((str(goban).rstrip())) # pylint: disable=C0325 time.sleep(T_INTERVAL)
def main(): """ Reads in a specified file, removes trailing whitespace, and re-saves. """ # Open file and store lines as str list try: file_handler = open(ARGS.filename, 'r+') except IOError: print(traceback.format_exc()) # pylint: disable=C0325 sys.exit() lines_of_text = file_handler.readlines() file_handler.seek(0) # Preview and write text back to file and close file print(lines_of_text) # pylint: disable=C0325 Cli.wait() string = '' preview_string = '' for index, _ in enumerate(lines_of_text): string += lines_of_text[index].rstrip() + '\n' preview_string = string.strip() + Cli.term_fx('b', 'EOL') pydoc.pipepager(preview_string, cmd='less -R') try: char = Cli.get_keypress('Write to file?') assert char == 'y' file_handler.write(string) except AssertionError: print('File not saved. Good bye.') # pylint: disable=C0325 finally: file_handler.close()
def work_with_p_files(cartesian): """ Writes instance to pickle file or loads instance from pickle file. """ #global file_list, pickle_list if ARGS and ARGS.infile: infile = ARGS.infile else: infile = 'save.p' current_dir = os.getcwd() file_list = os.listdir(current_dir) filemenu_list = ['..', 'save as pickle', 'open a pickle file'] if infile in file_list: filemenu_list.append("reopen '" + infile + "'") menu1 = PlainList(filemenu_list) #pickle_list = [] sel1 = Cli.make_page('pickle', cartesian, lambda: SHELL.list_menu(menu1)) if sel1 == 2: cartesian.save_p_file(BASENAME) elif sel1 != 1: cartesian = Cli.open_p_file() return cartesian
def main(): """ Takes a space-delimited int list (e.g., '1 2 3 4 5 6 7 8 9 10 11 12') as input; generates and ouputs an ASCII diagram. * It might be good to define more functions. """ # SHELL.welcome('Draw Tonerow', 'draw a diagram of a 12-tone row') in_str = Cli().input(prompt='') str_list = in_str.split() int_list = [int(s) for s in str_list] out_str = '\n' out_str += '\n ' + str(int_list) out_str += '\n' + '=' * 41 + '\n' out_str += '\n' for row in range(12): str_row = ' {:>2} '.format(12 - row) for index in range(12): if int_list[index] == 12 - row: str_row += '[X]' else: str_row += '. .' out_str += str_row + '\n' out_str += '\n' SHELL.output(out_str)
def play_thru(self, autoplay=False): goban = Goban(int(self.header_dict['SZ'])) #, skinfile=self.skin) color = 'black' for _, turn in enumerate(self.moves): goban.place_stone(turn[0], int(turn[1:]), color) if autoplay: func = lambda: time.sleep(.25) else: func = Cli.wait Cli.make_page(self.label, str(goban), func) if color == 'white': color = 'black' elif color == 'black': color = 'white'
def main(): """ Print welcome message then get pizza size and price and output area and unit price. """ Cli.print_header() print_welcome() while True: diameter = set_diameter(ABBREV) pizza = make_circle(diameter) pizza = _set_area_units(pizza) price = set_price() output_results(pizza, price)
def main(): """ Produce output and print to pager. """ dummy = TextGen() print('') # pylint: disable=C0325 text_str = '' for _ in range(PARAS): pgraph = Paragraph(dummy.chunk(), int(Cli.width() * 0.6), True) pgraph.set_lmargin(Cli.width() // 5) text_str += str(pgraph) if PAGER is True: Cli.less(text_str) else: print(text_str) # pylint: disable=C0325
def main(): """ In a text environment, roll one die with or without animation, according to command-line flags. In Tk, run the main loop. """ if SHELL.interface == 'Tk': SHELL.main_window.mainloop() else: while True: if SHELL_NAME in ['bash', 'sh']: if ARGS is not None and ARGS.anim: die.animate() else: roll_and_output() Cli.wait() Cli.clear(9)
def __init__(self, sgf_str='', skin='unicode1.json'): # Parent constructor super(GoGame, self).__init__() # Declare a new dictionary self.header_dict = {} # If an sgf string is given... if len(sgf_str) > 0: # Split it up into units self.units = sgf_str.split(';') # Get the header string self.units = self.units[1:] self.header_str = self.units[0] # Get the list of moves and self.moves = self.units[1:] # Strip off any whitespace self.moves = [move.strip() for move in self.moves] # Convert the header information to a dictionary self.head_list = self.header_str.split(']')[:-1] for unit in self.head_list: l = unit.split('[') l = [i.strip() for i in l] self.header_dict.update({l[0]:l[1]}) self.size = eval(self.header_dict['SZ']) #there is a better way i think # Convert the sgf representations to Turn objects for i, v in enumerate(self.moves): if self.moves[i][0] == 'B': colour = 'black' elif self.moves[i][0] == 'W': colour = 'white' address = (self.moves[i][2].upper(), self.size - (ord(self.moves[i][3]) - 97)) self.moves[i] = Turn(colour, address, self.moves[i][5:]) else: # If this is a new game, there will be no header. So let's make one. black_player = Cli.input("Black player's name: ") white_player = Cli.input("White player's name: ") self.header_dict.update({'SZ': 19, 'PW': white_player, 'PB': black_player, 'KM': 6.5, 'GM':1})
def main(): """Launch an interface, i.e., main loop.""" if SHELL.interface == 'Tk': SHELL.main_window.mainloop() else: while True: f = lambda: SHELL.list_menu(MENU_OPTS) action = Cli.make_page(func=f) if action == 1: scriptname = choose_file(SCRIPT_LIST) MENU_OPTS.items[0] = scriptname elif action == 2: shell_name = select_shell(SHELL_LIST) MENU_OPTS.items[1] = shell_name elif action == 3: pass elif action == 4: try: run_script(scriptname, shell_name) except KeyboardInterrupt: continue elif action == 5: open_in_editor(scriptname) elif action == 6: sys.exit(0)
def access_gnugo_functs(self, basename): """ Scoring/estimating tools from gnugo; this should take filename instead. """ Cli.make_page( 'WRITE FILE: {}.sgf'.format(basename), self, lambda: self.write_sgf( basename)) menu1 = ListPrompt(['..', 'fast', 'medium', 'slow']) sel1 = Cli.make_page('MENU: GNUGO Scoring Tools', self, menu1.input) gnugo_dict = {'fast':'estimate', 'medium':'finish', 'slow':'aftermath'} print('') #pylint: disable=C0325 if sel1 != 1: os.system('gnugo --score ' + gnugo_dict[menu1.items[sel1 - 1]] +\ ' --quiet -l {}.sgf'.format(basename)) Cli.wait()
def fill(): """ Call the graphs fill() method and refresh the text of the message widget. """ graph.fill(graph.color_chooser()) SHELL.msgtxt.set(Cli.ul(graph.label.title(), width=SIZE*2+6) + str(graph))
def load_p_file(): """load pickle file with Tk""" global graph graph = SHELL.open_p_file() SHELL.msgtxt.set( Cli.ul(graph.label.title(), width=SIZE*2+6) + str(graph)) graph.sh_obj = SHELL
def file_actions(cartesian): """ work with files: open or save """ sel1 = Cli.make_page( 'MENU: File Actions', cartesian, lambda: SHELL.list_menu(FILE_OPTS)) if sel1 == 2: cartesian.write_txt(BASENAME) elif sel1 == 3: cartesian.write_sgf(BASENAME) elif sel1 == 4: cartesian.save_p_file(BASENAME) elif sel1 == 5: cartesian = Cli.open_p_file() # A = A.__class__.open_p_file() elif sel1 == 6: cartesian = work_with_p_files(cartesian) return cartesian
def main(): """ Get stdin, echo translation to stdout. """ Cli.clear() while True: words = [word.strip(".").strip().lower() for word in Cli.input().split()] if words == [":get-list"]: list_ = [w.encode("ascii") for w in list(TRANSLATE_KEY.keys())] print("\n{}".format(sorted(list_, key=str.lower))) # pylint: disable=C0325 continue output = "" for word in words: output += TRANSLATE_KEY[word] + " " print("{}.\n".format(output.encode("utf-8").capitalize().strip())) # pylint: disable=C0325
def add_polynomial(): """ Dispatches appropriate dialogs, then plots polynomial, adding it to the polynmial list. """ graph.add_polynomial() SHELL.msgtxt.set( Cli.ul(graph.label.title(), width=SIZE*2+6) + str(graph))
def new_graph(): """ Load JSON skinfile if specified and create a new goban instance """ if ARGS is not None and ARGS.skin is not None: plane = Goban(sh_obj=SHELL, size=SIZE, skinfile=ARGS.skin) else: plane = Goban(size=SIZE, sh_obj=SHELL) SHELL.msgtxt.set(Cli.ul(plane.label.title(), width=SIZE*2+6) + str(plane)) return plane
def plot_point(): """ Calls color-chooser dialog, and dialog prompts, then plots point. """ color = graph.color_chooser() graph.prompt_point(color) SHELL.msgtxt.set( Cli.ul(graph.label.title(), width=SIZE*2+6) + str(graph))
def main(): """ Feed fortunes to the selected ASCII character. """ parse_help_flag() Cli() cow = '' message1 = define_text() cow_num = Cli.make_page('UP NEXT: {}'.format(message1), '', MENU_FUNC) while True: message2 = message1 message1 = define_text() cow = LIST_OBJ[cow_num - 1] ascii_cow = subprocess.check_output( 'echo "{}"|cowsay -f {}'.format(message2, cow), shell=True) ascii_cow = "\n\n{}\n\n".format(ascii_cow) Cli.make_page('UP NEXT: {}'.format(message1), ascii_cow, Cli.wait) cow_num = Cli.make_page('UP NEXT: {}'.format(message1), '', MENU_FUNC)
def main(): """ Gets the user's choice and gives them a preview. """ _first_pass = True art = '' if __name__ == '__main__': while True: if SHELL.interface in ['dialog'] and not _first_pass: Cli.wait() else: _first_pass = False #selection = Cli.make_page(obj='\n' + art, func=menu_func) selection = Cli.make_page( obj='\n' + art, func=lambda: SHELL.list_menu(LIST_OBJ)) if selection == -1: break figlet_font = FONT_OPTIONS[selection - 1] art = subprocess.check_output('toilet --gay -f {} "{}"'.format( figlet_font, PHRASE), shell=True)
def main(): """ user can create a collection of Thing objects """ things = [] label_pile = [str(thing) for thing in things] enum = Enumeration(label_pile, 'Inventory') # Start Screen SHELL.welcome( 'Things', 'This is a test/demonstration of my cjh.shell module and Thing class.') print('') # pylint: disable=C0325 selection = SHELL.list_menu(MAIN_MENU) while True: if selection == 1: name = form( enum, selection, lambda: SHELL.input('\nName of thing: ')) something = Thing() something.label = name things.append(something) elif selection == 2: form(enum, selection, Cli.wait) elif selection == 3: discard_menu = ListPrompt(label_pile) if len(things) > 0: print('Choose a <Thing> to Discard.') # pylint: disable=C0325 discard = form( enum, selection, lambda: discard_menu.input(hidden=True)) things.remove(things[discard - 1]) elif selection == 4: print('\n') # pylint: disable=C0325 sys.exit('Good bye.') label_pile = [str(thing) for thing in things] enum = Enumeration(label_pile, 'Inventory') selection = Cli.make_page( header='Main Menu', obj=str(enum) + Cli.hrule( width=.333, string=True), func=lambda: SHELL.list_menu(MAIN_MENU))
def select_shell(shell_list_): """ Select shell to use. """ if SHELL.interface == 'bash': listobj = AbstractList(shell_list_) shell_menu = lambda: SHELL.list_menu(listobj) number = Cli.make_page(func=shell_menu) shell_name_ = shell_list_[number - 1] elif SHELL.interface == 'Tk': shell_name_ = shellvar.get().strip() return shell_name_
def main(): """ Writes requested modifications to the 'config.json' file, and sends some kind of feedback to stdout. """ if ARGS.s is not None: CONFIG.write_to_config_file(shell=ARGS.s) if ARGS.e is not None: CONFIG.write_to_config_file(editor=ARGS.e) if ARGS.t is not None: CONFIG.write_to_config_file(terminal=ARGS.t) if ARGS.l is not None: CONFIG.write_to_config_file(language=ARGS.l) # config_dict = {'shell':shell} # with open(filename, 'w') as outfile: json.dump( # config_dict, outfile, indent=2) string = '' if (ARGS.v >= 1 and ARGS.s is not None) or not ( ARGS.e or ARGS.s or ARGS.t or ARGS.l): string += "\n shell: '{}'".format(shell) if (ARGS.v >= 1 and ARGS.e is not None) or not ( ARGS.e or ARGS.s or ARGS.t or ARGS.l): string += "\n editor: '{}'".format(editor) if (ARGS.v >= 1 and ARGS.t is not None) or not ( ARGS.e or ARGS.s or ARGS.t or ARGS.l): string += "\nterminal: '{}'".format(terminal) if (ARGS.v >= 1 and ARGS.l is not None) or not ( ARGS.e or ARGS.s or ARGS.t or ARGS.l): string += "\nlanguage: '{}'".format(language) if len(string) > 0: print(string + '\n') # pylint: disable=C0325 if (ARGS.v >= 2) or ( not (ARGS.e or ARGS.s or ARGS.t or ARGS.l) and ARGS.v >= 1): Cli.view_source(FILENAME) if ARGS.s or ARGS.e or ARGS.t or ARGS.l: Cli.report_filesave(FILENAME)
def main(): """ Lets user browse and preview skins for the Goban class. """ goban = Goban(sh_obj=SHELL, size=9) if __name__ == '__main__': while True: choice = Cli.make_page(func=lambda: SHELL.list_menu(LIST_OBJ)) skinfile = LIST_OBJ[choice - 1] try: if SHELL.py_version == 2: goban.skin_dict = json.load(open('skins/' + skinfile, 'rb')) elif SHELL.py_version == 3: file_ptr = open('skins/{}'.format(skinfile), 'rb') text_buffer = file_ptr.read().decode('utf-8') goban.skin_dict = json.loads(text_buffer) except IOError: Cli.text_splash(Cli.box("File Error with '{}'".format( skinfile)), duration=0) SHELL.wait() continue goban.cursor = [0, 0] Cli.text_splash("== Now give '{}' a try! ==".format( skinfile), duration=1, flashes=4) goban.view_edit()
def __init__(self, filename, skin="unicode1.json"): super(GameRecord, self).__init__() GoGame.count = 0 self.headers = [] self.games = [] # Read file into buffer self.buffer_ = Cli.cat(files=[filename], quiet=True, return_str=True) self.chunks = self.buffer_.split('(')[1:] for chunk in self.chunks: self.games.append(GoGame(chunk))
def _initialize_fields(): self.margin = margin self.width = Cli.width() - margin * 2 self.tabpoints = margin, self.width self.author = None self.title = None self.date = '' self.buffer = '' self.lines = [] self.pgraph_no = 0 self.section_no = 0 self.p_list = [] self.s_list = []
def graph_operations(cartesian): """ Functions relating to the board: edit it, trash it, view it with an external viewer. """ plane_response = Cli.make_page( 'MENU: Plane', cartesian, lambda: SHELL.list_menu(PLANE_OPTS)) if plane_response == 2: cartesian.view_edit() elif plane_response == 3: try: color = cartesian.color_chooser() cartesian.fill(color) except KeyboardInterrupt: pass elif plane_response == 4: if ARGS and ARGS.external: Cli.make_page( 'FILE: {}.sgf'.format(BASENAME), cartesian, lambda: cartesian.write_sgf(BASENAME)) # View board (with external app). If gnugo is specified, append the #appropriate flags. if ARGS and ARGS.external == 'gnugo': proc = subprocess.Popen( 'gnugo --mode ascii --quiet -l {}.sgf'.format(BASENAME), shell=True) else: proc = subprocess.Popen( '{} {}.sgf'.format(ARGS.external, BASENAME), shell=True) proc.wait() # Trash board and create a new one the same size else: cartesian = _make_graph() elif plane_response == 5: cartesian = _make_graph() return cartesian
def main(): """ Prompt user for a string, then echo it back in bold. """ Cli() # Input txt = SHELL.input( {'EN': 'Something to bolden: ', 'EO': 'Teksto por grasigi: '}[LANG]) # Output if SHELL.interface in ['sh', 'bash', 'dialog', 'SL4A', 'zenity']: Cli.term_fx('bp', txt) elif SHELL.interface in ['Tk']: total_width = len(txt) * AVG_CHAR_WIDTH + 45 SHELL.center_window(height_=90, width_=total_width, y_offset=100) SHELL.main_window.config(bg='white') SHELL.msg.config( bg='white', width=total_width, font=('serif', 36, 'bold', 'italic')) SHELL.msgtxt.set(txt) SHELL.main_window.title(txt) SHELL.main_window.mainloop()
def main(): """ the main function """ #fx_list = [] if ARGS is not None and ARGS.quiet is False: SHELL.welcome( script_name='== simple graph calc ==', description='A simple text-based graphing calculator.') graph = _make_graph() # if there is an --infile, open graph in editor if ARGS is not None and ARGS.infile is True: graph.view_edit() # Main Loop while True: if SHELL.interface in ['bash']: Cli.clear() # Will this work on SL4A? main_response = Cli.make_page( 'MENU: Main', graph, lambda: SHELL.list_menu(MAIN_OPTS)) print(main_response) #use try keyboard interrupt if main_response == 1: graph = graph_operations(graph) elif main_response == 2: graph = functions_menu(graph) elif main_response == 3: graph.access_gnugo_functs(BASENAME) elif main_response == 4: graph = file_actions(graph) else: break