def launch_game(stdscr, world, settings_dict): stdscr.clear() try: settings_dict = game_main.game_main(stdscr,world, settings_dict) except Exception as e: curses.reset_shell_mode() print('Error occured') print(type(e)) print(e.args) tb = traceback.format_exc() print(tb) print('') print('I''m sorry =(. Thank you for playing though.') print('') print('Typical things that cause this are:') print(' > Resizing the window to be too small') print('Please don''t do these things') input('Press Enter to continue, and the game will return to the main menu.') curses.reset_prog_mode() finally: # Then reboot main setup window_setup(stdscr) # Return the settings dictionary return settings_dict
def mywrapper(func, *args, **kwds): """This is a modified copy of the curses.wrapper() function Wrapper function that initializes curses and calls another function, restoring normal keyboard/screen behavior on error. The callable object 'func' is then passed the main window 'stdscr' as its first argument, followed by any other arguments passed to wrapper(). """ res = None try: # Initialize curses stdscr=curses.initscr() curses.def_shell_mode() curses.noecho() curses.cbreak() stdscr.keypad(1) try: curses.start_color() except: pass return func(stdscr, *args, **kwds) finally: # Set everything back to normal stdscr.keypad(0) curses.echo() curses.nocbreak() # I added the def_shell_mode and restore: curses.reset_shell_mode() curses.endwin()
def shell_mode(self): self.lock.acquire() try: self.active=False curses.reset_shell_mode() finally: self.lock.release()
def createStepperProgram(self): top = panel.top_panel() menu = top.userptr() menu.window.clear() menu.window.refresh() curses.reset_shell_mode() prog = [] build = 1 speed = 0 revolutions = 0 while build: while True: try: speed = int(raw_input('Enter Speed (-160 - 160 RPM: ')) if speed >= -160 and speed <= 160: break else: print "Speed out of range. Try again..." except Exception as e: print "Invalid input for speed. Try again..." continue while True: try: revolutions = abs(float(raw_input('Enter Revolutions: '))) break except Exception as e: print "Invalid input for revolutions. Try again..." continue while True: cont = raw_input( 'Would you like to additional steps to your program? (Yes/No)' ).lower() if cont == "yes" or cont == "y": break elif cont == "no" or cont == "n": build = 0 break else: print "Invalid input... Try again." prog.append([speed, revolutions]) fileName = raw_input('Please enter the name of the program:') with open("programs/" + fileName + ".pgm", 'wb') as f: pickle.dump(prog, f) print "Created file " + fileName print tabulate(prog, headers=["speed", "revolutions"]) raw_input('Hit enter to continue:') curses.reset_prog_mode() menu.window.clear() menu.window.refresh() curses.doupdate()
def matrix(self, args): try: core.matrix.main() except KeyboardInterrupt: curses.endwin() curses.curs_set(1) curses.reset_shell_mode() curses.echo()
def _escape_progress_bar(self): ''' Properly exit the counter ''' sys.stdout.write('\n') curses.curs_set(1) curses.reset_shell_mode() return
def read_string_readline(self, prompt): self.scr.move(self.h, 0) self.scr.clrtoeol() self.scr.refresh() curses.reset_shell_mode() s = input(prompt) curses.reset_prog_mode() self.scr.redrawwin() return s
def exitCurses(self, stdscr): # Ende curses.nocbreak() stdscr.keypad(0) curses.echo() curses.endwin() # cannot restore normal mode after curses-exit, wtf? curses.reset_shell_mode() print "ending radio session"
def do(self): curses.reset_shell_mode() subprocess.call(self.path + '/do.sh', shell=True) str_end = '[INSTALLER] Task ' + str( self.name) + ' finished, press key to continue' print('_' * len(str_end) + '\n') print(str_end) curses.reset_prog_mode()
def clean_curses(): """Resume normal shell state. Does nothing if curses wasn't initialized.""" try: curses.reset_shell_mode() except curses.error: pass try: curses.endwin() except curses.error: pass
def RestoreScreen(): for x in sys.argv: # avoid curses library with the --no-curses option. if (x == "--no-curses"): return curses.reset_shell_mode() curses.nocbreak() gb.scrn.keypad(0) curses.echo() curses.endwin()
def run(seconds): steps = 0 scr = curses.initscr() scr.nodelay(1) curses.curs_set(0) curses.noecho() curses.start_color() curses.use_default_colors() color_char_normal = 1 color_char_highlight = 2 curses.init_pair(color_char_normal, curses.COLOR_GREEN, curses.COLOR_BLACK) curses.init_pair(color_char_highlight, curses.COLOR_WHITE, curses.COLOR_GREEN) height, width = scr.getmaxyx() lines = [] min_speed = 1 max_speed = 6 for i in range(50): line = FallingChar(width, min_speed, max_speed, color_char_normal, color_char_highlight) line.y = random.randint(0, height - 3) lines.append(line) scr.refresh() start = time.time() fps = 25 while True: height, width = scr.getmaxyx() for line in lines: line.tick(scr, steps) for i in range(100): x = random.randint(0, width - 2) y = random.randint(0, height - 2) scr.addstr(y, x, ' ') scr.refresh() if scr.getch() != -1: break if (time.time() - start) >= seconds: break time.sleep(1.0 / fps) steps += 1 curses.endwin() curses.curs_set(1) curses.reset_shell_mode() curses.echo()
def addUser(self): top = panel.top_panel() menu = top.userptr() menu.window.clear() menu.window.refresh() curses.reset_shell_mode() userdb.cliAddUser() self.updateAdminMenu() curses.reset_prog_mode() menu.window.clear() menu.window.refresh()
def main(): global stdscr dir(curses) stdscr = curses.initscr() # initialize ncurses display stdscr.nodelay(1) # dont wait for key presses curses.noecho() # dont echo key presses GZ.spi_set_width(2) # Pass blocks of 2 bytes on SPI stdscr.erase() stdscr.addstr("Toggling all outputs.\n") stdscr.addstr("Press 'n' for next test, any other key to stop.\n") key = 0 while (True): exercise_outputs(0xff, 0x00) key = stdscr.getch() if (key != -1): break if (str(unichr(key)) == "n"): stdscr.erase() stdscr.addstr("Toggling alternate outputs.\n") stdscr.addstr("Press 'n' for next test, any other key to stop.\n") while (True): exercise_outputs(0xaa, 0x55) key = stdscr.getch() if (key != -1): break if (str(unichr(key)) == "n"): stdscr.erase() stdscr.addstr("Walking outputs.\n") stdscr.addstr("Press 'n' for next test, any other key to stop.\n") current = 0xfffe while (True): exercise_outputs(current, (current << 1) | 0x0001) current = (current << 2) | 0x03 if ((current & 0xff) == 0xff): current = 0xfe key = stdscr.getch() if (key != -1): break if (str(unichr(key)) == "n"): stdscr.erase() curses.curs_set(0) # Hide the cursor stdscr.addstr("Reading inputs.\n") stdscr.addstr("Press any key to stop.\n") while (True): display_inputs() key = stdscr.getch() if (key != -1): break stdscr.move(stdscr.getyx()[0] + 1, 0) curses.curs_set(1) stdscr.refresh() GZ.spi_close() # close SPI channel curses.reset_shell_mode() # turn off ncurses return 0
def main(): global stdscr dir(curses) stdscr = curses.initscr() # initialize ncurses display stdscr.nodelay(1) # dont wait for key presses curses.noecho() # dont echo key presses GZ.spi_set_width(2) # Pass blocks of 2 bytes on SPI stdscr.erase() stdscr.addstr("Toggling all outputs.\n") stdscr.addstr("Press 'n' for next test, any other key to stop.\n") key = 0 while(True): exercise_outputs(0xff, 0x00); key = stdscr.getch() if (key != -1): break; if (str(unichr(key)) == "n"): stdscr.erase() stdscr.addstr("Toggling alternate outputs.\n") stdscr.addstr("Press 'n' for next test, any other key to stop.\n") while(True): exercise_outputs(0xaa, 0x55) key = stdscr.getch() if (key != -1): break; if (str(unichr(key)) == "n"): stdscr.erase() stdscr.addstr("Walking outputs.\n") stdscr.addstr("Press 'n' for next test, any other key to stop.\n") current = 0xfffe while(True): exercise_outputs(current, (current << 1) | 0x0001) current = (current << 2) | 0x03 if ((current & 0xff) == 0xff): current = 0xfe key = stdscr.getch(); if (key != -1): break; if (str(unichr(key)) == "n"): stdscr.erase() curses.curs_set(0) # Hide the cursor stdscr.addstr("Reading inputs.\n") stdscr.addstr("Press any key to stop.\n") while(True): display_inputs() key = stdscr.getch() if (key != -1): break; stdscr.move(stdscr.getyx()[0] + 1 ,0) curses.curs_set(1) stdscr.refresh() GZ.spi_close() # close SPI channel curses.reset_shell_mode() # turn off ncurses return 0
def addEmail(self): top = panel.top_panel() menu = top.userptr() menu.window.clear() menu.window.refresh() curses.reset_shell_mode() email = raw_input("Email address:") userdb.editEmail(self.curUserName, email) curses.reset_prog_mode() menu.window.clear() menu.window.refresh() self.print_msg(email + " added", 10, 10)
def shell_cmd(scr, cmd, args): scr.clear() scr.refresh() curses.reset_shell_mode() if args == None: args = "" cmd = cmd[1:] os.system("{} {}".format(cmd, args)) input("\nPress any key to return to program...") curses.reset_prog_mode() scr.clear() cdraw(scr)
def changePassword(self): top = panel.top_panel() menu = top.userptr() menu.window.clear() menu.window.refresh() curses.reset_shell_mode() userdb.cliChangePassword(self.curUserName, 1) userdb.resetPassword(self.curUserName) curses.reset_prog_mode() menu.window.clear() menu.window.refresh() self.print_msg(self.curUserName + " Password Changed", 10, 10)
def replyEmailApp(MainSession, emlData, currentSelect, stdscr): curses.def_prog_mode(); stdscr.clear(); stdscr.refresh() curses.reset_shell_mode(); print PROC_ORIGINAL msgCodec = Proc(MainSession.IMAP.fetchMsg(\ emlData[3][currentSelect])[1][0][1]) # Fetch original Msg toSendMsg = constructReply(MainSession, msgCodec) # Gather reply MIME if toSendMsg == None: # User cancelled sending curses.reset_prog_mode(); stdscr.clear(); stdscr.refresh() return emlData try: MainSession.SMTP.session.sendmail(toSendMsg["From"], ParseAddr(toSendMsg["To"])[1], toSendMsg.as_string()) except Exception as err: print SEND_ERR % err; raw_input() else: # If sending is successful, then ask whether save to draft.
def play(contexts): """Play back a sequence of `contexts`.""" try: win = curses.initscr() curses.start_color() curses.use_default_colors() curses.noecho() for context in contexts: # transition effect if context.transition is not None: if isinstance(context.transition, int): for _ in xrange(context.transition): curses.flash() curses.delay_output(350) else: y, x = win.getmaxyx() for i in xrange(x): for j in xrange(y): if i != x-1 or j != y-1: win.addch(j, i, ord(context.transition)) win.refresh() curses.delay_output(7) # load next slide curses.delay_output(200) curses.curs_set(context.cursor) win.clear() context.prepare(win) # mainloop while 1: c = win.getch() try: context.process(win, c) except Exception: break # finished y, x = win.getmaxyx() outro = " Press ESC to exit presentation mode. " win.addnstr(y-1, max(0, x-len(outro)-1), outro, x-1, curses.A_REVERSE) while 1: c = win.getch() if c == 27: break except KeyboardInterrupt: pass finally: curses.reset_shell_mode() curses.endwin()
def launch_edit(self,filename): """ Starts a text editor on a named file """ if sys.platform[:3] == "win": editor = os.getenv("EDITOR","edit") else: editor = os.getenv("EDITOR","vi") #Save and restore curses mode. # =Can't guarantee - curses is availble. if self.in_curses: curses.reset_shell_mode() os.system(editor +" "+ filename) if self.in_curses: curses.reset_prog_mode()
def smartCommand(stdscr, MainSession, Appdata, event): (maxY,maxX) = stdscr.getmaxyx() curses.raw(); curses.cbreak(); curses.curs_set(1); curses.setsyx(0,0) stdscr.erase(); stdscr.refresh(); curses.reset_shell_mode() SmartModeInstruct(maxX) command = raw_input(">> ") while True: if command.lower() in Q_LIST: break elif command.lower() in H_LIST: SmartModeInstruct(maxX) elif command.lower() in I_LIST: displayInbox(MainSession, stdscr) elif command.lower() in S_LIST: searchMailApp(MainSession, stdscr) elif command.lower() in N_LIST: sendMailApp(MainSession) elif command != "": parseSmart(MainSession, command, stdscr) command = raw_input(">> ") exitApp(stdscr)
def last_main(): curses.endwin() curses.curs_set(1) curses.reset_shell_mode() curses.echo() screen = curses.initscr() color() lastchr = string.join(list(MATRIX_THANKS_CHARS), " ") last_height, last_width = screen.getmaxyx() start_width = last_width / 2 - len(lastchr) / 2 for i in range(last_height / 2): screen.clear() screen.addstr(i, start_width, lastchr, curses.color_pair(1)) screen.refresh() time.sleep(0.2) screen.getch() curses.endwin()
def update(self, clear=True): curses.def_prog_mode() curses.reset_shell_mode() sys.stdout.write('\033[2J') sys.stdout.write('\033[H') def bool_map(v): return "On" if v else "Off" sys.stdout.write( "[a]ntialiasing: {} [d]ither: {} [f]it horizontal: {}\n".format( bool_map(self.antialiasing), bool_map(self.dither), bool_map(self.fit))) for i in range( self.start_display_at, self.start_display_at + min(len(self.values) - self.start_display_at, self.height - 2)): sys.stdout.write(self.values[i]) sys.stdout.write("\n") curses.reset_prog_mode()
def teardown_console(stdscr, tcattr): stdscr.keypad(False) curses.nocbreak() curses.curs_set(1) curses.echo() # Nothing says what this does and does not record and reset # So I'm still going to unwind my changes curses.reset_shell_mode() # curses.endwin() # We don't seem to reset out colors. It *might* not be possible to know what current colors are # But I don't buy that, there's an escape code for everything # Ehhhhhh maybe not. Let's just do a reset # TBH I'm not sure why I'm bothering asking curses when I know what I'm gonna get back # I'm so mad at curses I never want to talk to it again # sys.stdout.write(curses.tparm(curses.tigetstr("sgr"), 0)) sys.stdout.write('\u001b[0m') # Something is still up with newlines after an exit, this seems to fix it # So we unwind curses, do a reset, and then just smash it with a hammer to be sure termios.tcsetattr(sys.stdout.fileno(), termios.TCSAFLUSH, tcattr)
def otherkey(self, c): if c in (ord('f'), curses.KEY_ENTER, 10): root.setpassive() self.render() elif c == ord('h'): root.setpassive() self.printhelp() elif c in (ord('d'), ord('D')): # if self.winmanager.issplit == True: # self.winmanager.unsetsplit() # else: # self.winmanager.setsplit() if self.winmanager.issplit == False: self.winmanager.setsplit() if root.isactive: self.doublewin.drawDoubleWin() # self.winmanager.setsplit = True root.setpassive() elif c == ord('s'): curses.def_prog_mode() curses.reset_shell_mode() self.shell()
def emailLister(MainSession, msgNOs, stdscr): curses.def_shell_mode(); curses.reset_prog_mode() # Back to curses curses.curs_set(0); stdscr.clear(); stdscr.refresh() # Init curses maxY, maxX = stdscr.getmaxyx(); stdscr.clear(); stdscr.box() stdscr.addstr(0, max(0, (maxX - len(JIMMY_MAIL)) / 2), JIMMY_MAIL) stdscr.addstr(min(2,maxY-1),max(0,(maxX-len(PLEASE_WAIT))/2),PLEASE_WAIT) stdscr.refresh() emlData = fetchList(MainSession, msgNOs, stdscr) # Retrieve Messages (maxDigit,flag,event,currentTop,currentSelect)=(digitNo(len(msgNOs)), True, None, 0, 0) while flag: maxY, maxX = stdscr.getmaxyx(); stdscr.clear(); stdscr.box() stdscr.addstr(0, max(0, (maxX - len(JIMMY_MAIL)) / 2), JIMMY_MAIL) # Draw the Email list by calling drawList(). drawList(MainSession, stdscr, emlData, currentTop, currentSelect) # Draw the footnotes by calling drawInstruction(). drawInstruction(MainSession, stdscr) event = stdscr.getch(); # Respond to key stroke events. (flag, event, currentSelect, currentTop, maxY, msgNOs, emlData) =\ emailListResponder(event, MainSession, emlData, currentSelect, currentTop, maxY, msgNOs, flag, stdscr) stdscr.clear(); stdscr.refresh() curses.reset_shell_mode(); curses.curs_set(1) # Restore to shell mode.
def __del__(self): curses.reset_shell_mode()
def signal_term_handler(signal, frame): print 'got SIGTERM' curses.reset_shell_mode() sys.exit(0)
def shut_down(self): self.window.clear() self.window.refresh() curses.curs_set(True) curses.reset_shell_mode()
def signal_handler(signal, frame): #Want to clean up CTRL+C action curses.reset_shell_mode(); print("\nJust because of that, the big one is going to hit now..."); sys.exit(0);
def clear_and_restore_terminal(self): # We want to clear the screen and restore the terminal mode before execing the login program import curses self.getForm('MAIN').erase() curses.curs_set(1) curses.reset_shell_mode()
def reset_shell(self): curses.reset_shell_mode()
# Initialize curses window = curses.initscr() # By default no logging logging = False # Time step. By default 0.01 seconds. step = 0.01 # Start curses application while(True): # Capture key presses try: c = window.getch() if c == ord('q') curses.reset_shell_mode() curses.endwin() exit(0) elif c == ord('l'): if logging: logging = False logfile.close() else: logging = True log_time = 0 dt = datetime.now() logfile = open(str(dt.month)+'_'+str(dt.day)+'_'+str(dt.hour)+'_'+str(dt.minute)+'.txt', 'a') except(curses.error): pass # Process each 'step' second time.sleep(step)
def suspend(self): curses.def_prog_mode() curses.reset_shell_mode() curses.endwin()
stdscr.addstr("Press 'n' for next test, any other key to stop.\n") GZ.spi_write(a & 0x5555) # Pass set up bytes to SPI while(True): for x in range(0, 15): if (GZ.output_get(x)): GZ.spi_reset(x); else GZ.spi_set(x); key = stdscr.getch() if (key != -1): break; if (str(unichr(key)) == "n"): stdscr.erase() curses.curs_set(0) # Hide the cursor stdscr.addstr("Reading inputs.\n") stdscr.addstr("Press any key to stop.\n") while(True): display_inputs() key = stdscr.getch() if (key != -1): break; stdscr.move(stdscr.getyx()[0] + 1 ,0) curses.curs_set(1) stdscr.refresh() GZ.spi_close() # close SPI channel curses.reset_shell_mode() # turn off ncurses return 0 if __name__ == '__main__': main()
def main(scr): reset(scr) init_colors() display_logo(scr) drawing = Drawing(scr) tutor = Tutor(scr) save_dir = directory_setup() pen_tips = " ~`!@#$%^&*()-_+=vvxxoo|\/[]{}'.:<>\"" while True: c = scr.getch() if c == ord("q"): # QUIT break elif c == curses.KEY_RESIZE: drawing.recenter() continue elif c == curses.KEY_UP: drawing.move_by(-1, 0) elif c == curses.KEY_DOWN: drawing.move_by(1, 0) elif c == curses.KEY_RIGHT: drawing.move_by(0, 1) elif c == curses.KEY_LEFT: drawing.move_by(0, -1) elif c == ord("c"): # CHANGE COLORS drawing.color_pair = (drawing.color_pair + 1) % 8 tutor.change_color() elif c == ord("n"): # NEW DRAWING reset(scr) drawing = Drawing(scr) tutor.new() continue # skip drawing: the new drawing should be empty elif c == ord("p"): # PEN UP/DOWN drawing.pen_down = not drawing.pen_down tutor.pen() elif c == ord("e"): # ERASE tutor.erase() drawing.erase_last() continue # skip drawing: that would negate the erase elif c == ord("r"): # REPLAY CURRENT DRAWING tutor.message("OK, now it's my turn!") drawing.replay() continue # skip drawing: that would add to it elif c == ord("s"): # SAVE CURRENT DRAWING try: drawing.save(save_dir) tutor.message("I saved your drawing!") except IOError: tutor.message( "Sorry, something went wrong.\nI couldn't save this drawing." ) elif c == ord("l"): # LOAD SAVED DRAWING try: drawing = Drawing(scr) tutor.message( "Here's a drawing you made!\n(Or someone made for you!)") drawing.load_random(save_dir) except IndexError: tutor.message( "There are no drawings to load!\nYou should save one first." ) continue # skip drawing: the cursor hasn't moved elif c == ord("D"): # DELETE if drawing.fname: os.remove(drawing.fname) tutor.message("Deleted %s" % drawing.fname) reset(scr) drawing = Drawing(scr) elif c == ord("?") or c == ord("h"): # HELP tutor.help() elif c in map(ord, pen_tips): # PEN TIP drawing.pen_tip = chr(c) elif c in map(ord, "01234567"): # COLOR SELECTION drawing.color_pair = int(chr(c)) elif c == curses.KEY_F3: # DEBUG # save terminal state for later: curses.savetty() # return to shell mode for debug session: scr.move(0, 0) curses.reset_shell_mode() scr.refresh() import pdb pdb.set_trace() # when debugging is finished, restore the previous state: curses.resetty() reset(scr) drawing.recenter() # draw a new 'pixel' at the current location with the current pen tip, # if the pen is down: drawing.draw()
def leaveCurses(): curses.reset_shell_mode() signal.signal(signal.SIGWINCH, signal.SIG_DFL)
def exit(): curses.echo() curses.nocbreak() curses.reset_shell_mode() curses.endwin()
def signal_term_handler(signal, frame): print 'got SIGINT, bailing\r\n' curses.reset_shell_mode() sys.exit(0)
if not 0 <= x+dx < 20: x, y = (10, 5) trail = [] score[int(dx < 0)] += 1 if score[int(dx < 0)] > 9: score = [0,0] for i in ( range(20)+range(20, 0, -1) )*4: s.push_frame(blend(empty_frame, gameover[int(dx < 0)], i/20.)) metronome.sync() frame = [ [BLACK] * 12 for j in xrange(10) ] score_frame = [ [BLACK] * 12 for j in xrange(10) ] draw_score(score_frame, score) draw_pads(frame) for i in range(50): s.push_frame(blend(score_frame, frame, i/50.)) metronome.sync() dx, dy = -dx, 1 frame = [ [(0,0,0)] * 12 for i in xrange(10) ] draw_pads(frame) draw_ball(frame) s.push_frame(frame) metronome.sync() finally: pass curses.reset_shell_mode()
def SIGINT_handler(signal, frame): curses.reset_shell_mode() curses.endwin() exit(0)
def print_banner(): """ Print animated startup banner. Style 3: Matrix-Curses - See how deep the rabbit hole goes. Copyright (c) 2012 Tom Wallroth http://github.com/devsnd/matrix-curses/ Used and modified under GNU GPL version 3 :return: None """ string = "Tinfoil Chat NaCl %s" % str_version system("clear") width, height = get_tty_wh() print((height / 2) - 1) * '\n' # Style 1 animation = sysrandint(1, 3) if animation == 1: i = 0 while i <= len(string): stdout.write("\x1b[1A" + ' ') stdout.flush() if i == len(string): print((width - len(string)) / 2) * ' ' + string[:i] else: rc = chr(randrange(32, 126)) print((width - len(string)) / 2) * ' ' + string[:i] + rc i += 1 sleep(0.03) # Style 2 if animation == 2: char_l = len(string) * [''] while True: stdout.write("\x1b[1A" + ' ') stdout.flush() st = '' for i in range(len(string)): if char_l[i] != string[i]: char_l[i] = chr(randrange(32, 126)) else: char_l[i] = string[i] st += char_l[i] print((width - len(string)) / 2) * ' ' + st sleep(0.004) if st == string: break # Style 3 if animation == 3: string = "Tinfoil Chat NaCl 0.16.1" dropping_chars = 50 random_cleanup = 80 min_speed = 3 max_speed = 7 sleep_ms = 0.005 scroll_chars = '' for a in range(32, 126): scroll_chars += chr(a) class FChar(object): list_chr = list(scroll_chars) normal_attr = curses.A_NORMAL highlight_attr = curses.A_REVERSE def __init__(self, o_width, speed_min, speed_max): self.x = 0 self.y = 0 self.speed = 1 self.char = ' ' self.offset = randint(0, self.speed) self.reset(o_width, speed_min, speed_max) self.completed = [] def reset(self, c_width, speed_min, speed_max): self.char = choice(FChar.list_chr) self.x = randint(1, c_width - 1) self.y = 0 self.speed = randint(speed_min, speed_max) self.offset = randint(0, self.speed) def get_completed(self): return self.completed def tick(self, scr, steps): win_h, win_w = scr.getmaxyx() if self.advances(steps): # If window was re-sized and char is out of bounds, reset self.out_of_bounds_reset(win_w, win_h) # Make previous char curses.A_NORMAL scr.addstr(self.y, self.x, self.char, curses.A_NORMAL) # Choose new char and draw it A_NORMAL if not out of bounds self.y += 1 if self.y == win_h / 2: indent_len = (win_w - len(string)) / 2 prepended_ind = (indent_len * ' ') final_string = prepended_ind + string + ' ' if self.x > indent_len - 1: try: self.char = final_string[self.x] self.completed.append(self.x) except IndexError: self.char = choice(FChar.list_chr) else: self.char = choice(FChar.list_chr) if not self.out_of_bounds_reset(win_w, win_h): scr.addstr(self.y, self.x, self.char, curses.A_NORMAL) def out_of_bounds_reset(self, win_w, win_h): if self.x > win_w - 2: self.reset(win_w, min_speed, max_speed) return True if self.y > win_h - 2: self.reset(win_w, min_speed, max_speed) return True return False def advances(self, steps): if steps % (self.speed + self.offset) == 0: return True return False # Use insecure but fast PRNG def rand(): p = sysrandint(0, 1000000000) while True: p ^= (p << 21) & 0xffffffffffffffff p ^= (p >> 35) p ^= (p << 4) & 0xffffffffffffffff yield p def randint(_min, _max): n = r.next() return (n % (_max - _min)) + _min def main(): steps = 0 scr = curses.initscr() scr.nodelay(1) curses.curs_set(0) curses.noecho() win_h, win_w = scr.getmaxyx() if win_w < len(string): raise KeyboardInterrupt window_animation = None lines = [] for _ in range(dropping_chars): fc = FChar(win_w, min_speed, max_speed) fc.y = randint(0, win_h - 2) lines.append(fc) scr.refresh() completion = [] delay = 0 while True: win_h, win_w = scr.getmaxyx() for line in lines: line.tick(scr, steps) completed = line.get_completed() for c in completed: if c not in completion: completion.append(c) if len(completion) >= len(string): if delay > 600: raise KeyboardInterrupt else: delay += 1 for _ in range(random_cleanup): x = randint(0, win_w - 1) y = randint(0, win_h - 1) indent_len = (win_w - len(string)) / 2 prepended_ind = (indent_len * ' ') if y == win_h / 2: if x < len(prepended_ind): scr.addstr(y, x, ' ') if x > len(prepended_ind + string): scr.addstr(y, x, ' ') else: scr.addstr(y, x, ' ') if window_animation is not None: if not window_animation.tick(scr, steps): window_animation = None scr.refresh() sleep(sleep_ms) steps += 1 try: r = rand() main() except KeyboardInterrupt: curses.endwin() curses.curs_set(1) curses.reset_shell_mode() curses.echo() system("clear") sleep(0.3) system("clear") return None
def curses_deinit(self): curses.reset_shell_mode() curses.endwin()
def _escape_progress_bar(self): sys.stdout.write('\n') curses.curs_set(1) curses.reset_shell_mode() return