def dialogue(prompt, hidden = False): """ Clears the screen, displays a prompt, """ credential = "" screen.erase() # Add the prompt such that it appears center-justified screen.addstr(int(height(screen) / 2), 0, stralign.alignC(prompt, width(screen))) screen.refresh() char = screen.getch() while not (char == 10): if (char == 27): curses.endwin() sys.exit() elif (char == 127): if not (credential == ""): credential = credential[:-1] else: credential += chr(char) # Add the input such that it appears center-justified underneath the prompt screen.addstr(int(height(screen) / 2) + 1, 0, stralign.alignC(hide(credential, hidden), width(screen))) screen.refresh() char = screen.getch() screen.erase() return credential
def launch(cmdparser): stdscr = curses.initscr() curses.cbreak() #curses.noecho() curses.echo() stdscr.keypad(1) stdscr.scrollok(True) stdscr.clear() stdscr.refresh() try: # Run your code here io = FakeStdIO(stdscr) sys.stdin = io sys.stdout = io cmdparser.stdout = io cmdparser.stdin = io cmdparser.cmdloop() finally: curses.nocbreak() stdscr.keypad(0) curses.echo() curses.endwin()
def main(argv): global mines, board args = map(int, argv[1:]) xw = int(args[0]) if args else 20 yw = int(args[1]) if len(args) > 1 else xw / 2 mines = int(args[2]) if len(args) > 2 else int(xw * yw / 20) board = [' ' * xw for i in range(yw)] mines = {(randint(0, xw), randint(0, yw)) : True for i in range(mines)} scr = curses.initscr() scr.keypad(1) curses.curs_set(0) curses.noecho() curses.mousemask(curses.ALL_MOUSE_EVENTS) while True: scr.clear() k = scr.getch() scr.addstr(yw + 2, 0, ': ' + str(k)) if k == 27: break elif k == curses.KEY_MOUSE: _, x, y, z, bstate = curses.getmouse() scr.addstr(y, x, ' '.join(str(v) for v in (z, bstate))) elif k == curses.KEY_DC: boom(scr) scr.clear() curses.endwin()
def display_playback_progress(): stdscr = curses.initscr() curses.noecho() curses.cbreak() stdscr.keypad(True) stdscr.nodelay(True) while not done_displaying: stdout.write('\033c\r\n') stdout.write('Ingesting Data :\r\n\n') stdout.write('\tDate Glob : ' + gap_glob + '\r\n') stdout.write('\tMax Playbacks : ' + str(num_playback_threads) + '\r\n\n') stdout.write('\tInstruments:\r\n') list_lock.acquire() for refdes in playback_list.keys(): stdout.write('\t\t' + refdes + ' ' + SPINNER_CHAR[playback_list[refdes]] + '\r\n') playback_list[refdes] += 1 if playback_list[refdes] == SPINNER_CHAR.__len__(): playback_list[refdes] = 0 list_lock.release() if not done_displaying: get_key_input(stdscr) stdscr.refresh() sleep(0.2) stdscr.keypad(False) curses.echo() curses.nocbreak() curses.endwin() stdout.write('\033c\n\r') stdout.write('\tIngest Log File : ' + ingest_log_filename + '\r\n') stdout.write('\tPlayback Log Files : ' + playback_logs_dir + '\r\n\n')
def quit(leave_message = "", exit_status= 0): curses.nocbreak() stdscr.keypad(0) curses.echo() curses.endwin() print leave_message sys.exit(exit_status)
def CursesMonitor(dev): stdscr = curses.initscr() curses.cbreak() Console = CursesDisplay(stdscr, dev) Console.monitor() curses.nocbreak() curses.endwin()
def main(scr): h, w = scr.getmaxyx() hghts = [h // 3 + (1 if 3 - h % 3 <= i else 0) for i in range(3)] pr = 0 wins = [] for i in hghts: wins.append(newwin(i, w, pr, 0)) pr += i for i in range(3): wins[i].box(0, 0) panels = [new_panel(i) for i in wins] update_panels() doupdate() x = 0 while x != ord('q'): x = scr.getch() wn = wins[0] wn.addstr(1, 1, "%x" % x) wn.addstr(2, 1, repr([ i for i in dir(wn) if not i.startswith('__')])[:w-3]) def_prog_mode() endwin() print(dir(wn)) reset_prog_mode() wins[0].refresh()
def main(): """ Main entry point for gunicorn_console. """ # Set up curses. stdscr = curses.initscr() curses.start_color() curses.init_pair(1, foreground_colour, background_colour) curses.noecho() stdscr.keypad(True) stdscr.nodelay(True) try: curses.curs_set(False) except: pass try: # Run main event loop until quit. while True: try: update_gunicorns() handle_keypress(stdscr) display_output(stdscr) curses.napms(int(screen_delay * 1000)) except KeyboardInterrupt: break finally: # Tear down curses. curses.nocbreak() stdscr.keypad(False) curses.echo() curses.endwin()
def close(self): """ clean up """ curses.nocbreak() self.stdscr.keypad(0) curses.echo() curses.endwin()
def __exit__(self, exc_type, exc_value, traceback): """Reverse curses settings and kill the stdscr""" curses.nocbreak() curses.echo() self.stdscr.keypad(0) self.stdscr.clear() curses.endwin()
def beep(): """ Does an audible beep sound Reference: http://de3.aminet.net/dev/src/clr.py.txt """ if sys.platform == 'linux2': for dev in ('/dev/audio', '/dev/oss', '/dev/dsp', '/dev/sound'): if os.path.exists(dev): try: audio = file(dev, 'wb') for i in xrange(250): audio.write(chr(32) * 4) audio.write(chr(0) * 4) audio.close() return except: pass try: import curses curses.initscr() curses.beep() curses.flash() curses.endwin() return except: dataToStdout('\a', True) else: dataToStdout('\a', True)
def end_interface(self): # {{{ self.stdscr.erase() self.stdscr.refresh() curses.curs_set(1) curses.nocbreak() curses.echo() curses.endwin()
def main(argv): def __call__(self): pass dlog = DebugLog("debug.log") dlog.msg("Logging started\n") stdscr = curses.initscr() curses.noecho() curses.cbreak() stdscr.keypad(1) curses.start_color() try: wl = WindowLogic(stdscr) wl.start() ci = CommandInterpreter(stdscr, wl) ci.start() except Exception as e: dlog.excpt(e) raise ci.join() dlog.msg("Command Interpreter joined.\n") wl.stop() wl.join() dlog.msg("Thread Fetcher joined.\n") curses.nocbreak() stdscr.keypad(0) curses.echo() curses.endwin() curses.resetty() dlog.msg("Terminal restored.\n")
def main(): open_message = 'SecLab is open :)' closed_message = 'SecLab is closed :(' authenticate() try: is_open = True stdscr = curses.initscr() curses.cbreak() curses.noecho() stdscr.keypad(1) key = '' stdscr.addstr(5,33,please_wait, curses.A_BLINK) stdscr.refresh() stdscr.addstr(5,33,opened, curses.A_NORMAL) post_status(authenticate(), open_message) while 1: key = stdscr.getch() stdscr.clear() if is_open: stdscr.addstr(5, 33, please_wait, curses.A_BLINK) stdscr.refresh() stdscr.addstr(5, 33, closed, curses.A_NORMAL) post_status(authenticate(), closed_message) else: stdscr.addstr(5,33,please_wait, curses.A_BLINK) stdscr.refresh() stdscr.addstr(5,33,opened, curses.A_NORMAL) post_status(authenticate(), open_message) is_open = not is_open finally: curses.endwin() authenticate().destroy_status(id=LAST_POST_ID)
def main(): if not sys.argv[1:]: print __doc__ sys.exit(0) cmd = " ".join(sys.argv[1:]) p = os.popen(cmd, "r") text = p.read() sts = p.close() if sts: print >>sys.stderr, "Exit code:", sts sys.exit(sts) w = curses.initscr() try: while True: w.erase() try: w.addstr(text) except curses.error: pass w.refresh() time.sleep(1) p = os.popen(cmd, "r") text = p.read() sts = p.close() if sts: print >>sys.stderr, "Exit code:", sts sys.exit(sts) finally: curses.endwin()
def killWindow(self): """restore terminal window""" curses.nocbreak() self.stdscr.keypad(0) curses.echo() curses.curs_set(1) curses.endwin()
def getwinsize(): # Use the curses module if installed try: import curses stdscr = curses.initscr() curses.endwin() rows, cols = stdscr.getmaxyx() return rows, cols except ImportError: pass # Nope, so deal with ioctl directly. What value for TIOCGWINSZ? try: import termios TIOCGWINSZ = termios.TIOCGWINSZ except ImportError: TIOCGWINSZ = 0x40087468 # This is Linux specific import struct, fcntl s = struct.pack("HHHH", 0, 0, 0, 0) try: x = fcntl.ioctl(sys.stdout.fileno(), TIOCGWINSZ, s) except IOError: return 80 rows, cols = struct.unpack("HHHH", x)[:2] return rows, cols
def exit(self): curses.nocbreak() self.stdscr.keypad(0) curses.echo() curses.endwin() print("Bye!") self.done = True
def results(winResult): global option global player if winResult != 'end': if option == '1': clientSock.send('en'.encode('utf-8')) clientSock.close() serverSock.close() elif option == '2': serverSock.send('en'.encode('utf-8')) serverSock.close() time.sleep(2) endwin() if winResult == 'first': print ("Player Ctrl wins!") elif winResult == 'second': print ("Player Esc wins!") elif winResult == 'quit': print ("The player has quit") exit() elif winResult == 'end': if option == '1': clientSock.close() serverSock.close() elif option == '2': serverSock.close() time.sleep(2) endwin() option = '4' player = 0
def run(self): if deep == 0: print('level 1 :', 1, '/', 1) return screen = curses.initscr() # 初始化终端界面输出窗口 maxFile = [0] * (self.deep + 1) while True: links = list(self.QLinks.__dict__['queue']) # 队列中每个URL此时的深度值 deeps = [x[1] for x in links] '''keys中元素是[deep值,次数], deep=0为最里子层,deep=n-1为父层''' keys = [[x, 0] for x in range(self.deep + 1)] n = len(keys) for d in deeps: keys[d][1] += 1 screen.clear() # 清屏,等待输出 count = 0 for d in range(1, n + 1): count += 1 if keys[n - d][1] > maxFile[d - 1]: maxFile[d - 1] = keys[n - d][1] screen.addstr(count, 0, 'level ' + str(d) + ' : ' + str(keys[n - d][1]) + ' / ' + str(maxFile[d - 1])) screen.refresh() # 使生效 time.sleep(0.2) total = functools.reduce(lambda x, y: x + y, [i[1] for i in keys]) totalMax = functools.reduce(lambda x, y: x + y, maxFile) if self.event.is_set(): curses.endwin() logging.info('Done at ' + time.ctime()) break
def retrieveDeletes(): fileList = getDeletedFiles() if len(fileList) > 1: gb.startrow = 0 gb.highlightlinenum = 1 displscreen(fileList) while True: c = gb.scrn.getch() if c == ord("q"): gb.highlightlinenum = 1 rerun() break elif c == curses.KEY_UP: updown(gb.UP, fileList) elif c == curses.KEY_DOWN: updown(gb.DOWN, fileList) elif c == ord("\n"): fileList = retrieveFile(fileList) if len(fileList) > 1: displscreen(fileList) else: gb.highlightlinenum = 1 gb.scrn.clear() curses.endwin() rerun() break else: gb.scrn.clear() curses.endwin() gb.scrn.addstr(0, 0, "No files to retrieve. Press any key to continue.") gb.scrn.getch() rerun()
def close(self): curses.curs_set(1) self.screen.immedok(False) self.screen.keypad(0) curses.nocbreak() curses.echo() curses.endwin()
def main(sys_args=None): if not sys_args: sys_args = sys.argv[1:] default_options = load_defaults() parser = arg_parser.ArgumentParser( description="Cerebro Command Line Interaction Tool") parser.add_argument( "--clustersitterurl", dest="clustersitter_url", help="URL to the root of the clustersitter", default=default_options.get('clustersitter_url')) args = parser.parse_args(sys_args) default_options['clustersitter_url'] = args.clustersitter_url write_defaults(default_options) # Silence misc. logging.getLogger() 'can't find handler' warnings logging.basicConfig() logging.getLogger().setLevel(logging.CRITICAL) cluster_data = ClusterState(default_options['clustersitter_url']) screen = ClusterManagementScreen(cluster_data) try: if not cluster_data.url: print "Couldn't find a running cluster sitter!" return screen.run() except: curses.endwin() import traceback traceback.print_exc()
def winch_handler(self, signum, stackframe): self.changeflag.set() curses.endwin() self.scrwin.refresh() self.scrwin = curses.newwin(0, 0, 0, 0) self._remake_window() self._display_messages()
def Go(self): key2Direction = {\ curses.KEY_UP : Vector((-1, 0)),\ curses.KEY_LEFT : Vector(( 0,-1)),\ curses.KEY_DOWN : Vector((+1, 0)),\ curses.KEY_RIGHT : Vector(( 0,+1)),\ } null = Vector((0, 0)) self.alive = True while self.alive: # Wait a little for keypress key = self.pad.getch() if key in key2Direction: if null != self.snakeDirection + key2Direction[key]: self.snakeDirection = key2Direction[key] elif ord('q') == key: self.alive = False break self.Increment() # Nuke curses self.pad.keypad(0) curses.curs_set(1) curses.echo() curses.endwin() return
def login(): curses.echo() scr.border(1) scr.addstr(2,2,"Host IP:", norm) ip = scr.getstr(2,10) scr.addstr(3,2,"Port #:", norm) port = scr.getstr(3,9,7) scr.addstr(4,2,"Database Name:", norm) db = scr.getstr(4,16,15) scr.addstr(5,2,"Username:"******"Password:"******"I'm sorry, a connection was not able to be made.", bold) scr.addstr(11,10," Press 'q' to quit, or enter to try again", bold) option = scr.getch() if option == 113: # press 'q' curses.endwin() #exits ncurses return 0 else: return 1
def websocket_app(environ, start_response): print('Connected') if environ["PATH_INFO"] == '/': ws = environ["wsgi.websocket"] w = curses.initscr() w.nodelay(1) w.keypad(1) print('Press ESC to quit') last_command = 0 while 1: a = w.getch() if a == 27: break if time.time() - last_command < 1: continue if a != -1: time.sleep(0.01) print(a) else: time.sleep(0.01) continue if a == curses.KEY_RIGHT: ws.send(serialize(float(1)), binary=True) last_command = time.time() if a == curses.KEY_UP: ws.send(serialize(float(0)), binary=True) last_command = time.time() curses.endwin()
def refresh_window(procs, procs_status): """Print results on screen by using curses.""" curses.endwin() templ = "%-6s %-8s %4s %5s %5s %6s %4s %9s %2s" win.erase() header = templ % ("PID", "USER", "NI", "VIRT", "RES", "CPU%", "MEM%", "TIME+", "NAME") print_header(procs_status) print_line("") print_line(header, highlight=True) for p in procs: # TIME+ column shows process CPU cumulative time and it # is expressed as: "mm:ss.ms" ctime = timedelta(seconds=sum(p._cpu_times)) ctime = "%s:%s.%s" % (ctime.seconds // 60 % 60, str((ctime.seconds % 60)).zfill(2), str(ctime.microseconds)[:2]) line = templ % (p.pid, p._username()[:8], p._nice, bytes2human(p._meminfo.vms), bytes2human(p._meminfo.rss), p._cpu_percent, round(p._mempercent, 1), ctime, p._name, ) try: print_line(line) except curses.error: break win.refresh()
def exitCurses(screen): curses.nocbreak() screen.keypad(OFF) screen.nodelay(OFF) curses.curs_set(ON) curses.echo() curses.endwin()
def printlist(scr): i = 2 l = 0 if hosts == []: parser() j = scr.getmaxyx() k = j[1]/43 # We can't scroll the list, yet if len(hosts) >= (k*(j[0]-1)): curses.nocbreak() curses.echo() curses.endwin() os.system("clear") sys.exit(-1) for item in hosts: line = "" listid = hosts.index(item) if k > 1: scr.addstr(i, 3+l*40, str(listid)) scr.addstr(i, 6+l*40, "- " +item) l=(l+1)%k if l==0: i=i+1 else: scr.addstr(i, 3, str(listid)) scr.addstr(i, 6, "- " +item) i=i+1 i = i+2 scr.addstr(i,6, "# ") return i
def cleanup(): curses.nocbreak() stdscr.keypad(0) curses.echo() curses.endwin()
import sys if __name__ == '__main__': try: import curses except ImportError: # Currently fails on conda on ppc64le sys.stderr.write("Python 'curses' module not found. Skipping test.\n") sys.exit(0) screen = curses.initscr() try: curses.cbreak() pad = curses.newpad(10, 10) size = screen.getmaxyx() pad.refresh(0, 0, 0, 0, size[0] - 1, size[1] - 1) finally: curses.nocbreak() curses.endwin()
def cleanup_curses(): '''Return the console to a usable state''' curses.echo() curses.nocbreak() curses.endwin() os.system("/usr/bin/clear")
def tear_down(): win.keypad(0) curses.nocbreak() curses.echo() curses.endwin()
def endcurses(): curses.nl() curses.echo() curses.noraw() curses.endwin()
def stop(self): """ Clean up console """ curses.nocbreak() self.screen.keypad(0) curses.echo() curses.endwin()
def tuiConfig(): screen = curses.initscr() height,width=screen.getmaxyx() tmp=[] curses.noecho() curses.cbreak() curses.start_color() screen.keypad(1) curses.init_pair(1,curses.COLOR_BLACK,curses.COLOR_CYAN) highlightText=curses.color_pair(1) normalText=curses.A_NORMAL max_row=height-2 x=0 while x!=ord("q"): box=curses.newwin(max_row+2,width,0,0) box.addstr(0,0,"*** KONFIGURACE ***", highlightText ) box.addstr(height-1,0,"-=[ klavesy 0-4 ]=-", highlightText ) cols,rows=conyxDBQuery("select key, description, value from config order by rowid asc") nlen=0 rn=0 for i in rows: if (len(str(i[1])) > nlen): nlen = len(str(i[1])) box.addstr(rn+2,0,"["+str(rn)+"] "+str(i[1])+" ") rn+=1 rn=0 for i in rows: if (i[0]=="rodicovsky_zamek"): if (i[2]=="1"): box.addstr(rn+2,nlen+5," -> " + "Zapnuty") else: box.addstr(rn+2,nlen+5," -> " + "Vypnuty") elif (i[0]=="rodicovsky_zamek_heslo"): box.addstr(rn+2,nlen+5," -> " + (len(str(i[2]))*"*")) else: box.addstr(rn+2,nlen+5," -> "+str(i[2])) rn+=1 #if (x==ord("0")): # if (rows[0][2]=="0"): # conyxDBGenDML('update config set value = "1" where key="rodicovsky_zamek"') # if (rows[0][2]=="1"): # conyxDBGenDML('update config set value = "0" where key="rodicovsky_zamek"') # box.addstr(height-2,0,"*** PROVEDENA ZMENA *** "+str(rows[0][2]), highlightText ) if (x==ord("0")): pass_prompt="*** ZADEJ HESLO: " box.addstr(height-2,0,pass_prompt) input_pass="" input_pass_display="" screen.refresh() box.refresh() while x!=ord('\n'): #x = screen.getch() x = ugetch(screen) if ((x>=ord("a") and x<=ord("Z")) or (x>=ord("0") and x<=ord("9"))): input_pass+=chr(x) input_pass_display+="*" box.addstr(height-2,0,pass_prompt+input_pass_display) screen.refresh() box.refresh() input_pass=input_pass.strip() if (input_pass==rows[1][2]): box.addstr(height-4,0,"ZADANO HESLO SOUHLASI, MENIM STAV ZAMKU...") if (rows[0][2]=="0"): conyxDBGenDML('update config set value = "1" where key="rodicovsky_zamek"') box.addstr(height-2,0,"*** RODICOVSKY ZAMEK ZAPNUT *** ", highlightText ) if (rows[0][2]=="1"): conyxDBGenDML('update config set value = "0" where key="rodicovsky_zamek"') box.addstr(height-2,0,"*** RODICOVSKY ZAMEK VYPNUT *** ", highlightText ) else: box.addstr(height-4,0,"ZADANO HESLO NESOUHLASI.") if (x==ord("2")): pass_prompt="*** ZADEJ HESLO: " club_prompt="ZADEJ SCHVALENY KLUB: " box.addstr(height-2,0,pass_prompt) input_pass="" input_pass_display="" allowed_club="" screen.refresh() box.refresh() while x!=ord('\n'): #x = screen.getch() x = ugetch(screen) if ((x>=ord("a") and x<=ord("Z")) or (x>=ord("0") and x<=ord("9"))): input_pass+=chr(x) input_pass_display+="*" box.addstr(height-2,0,pass_prompt+input_pass_display) screen.refresh() box.refresh() input_pass=input_pass.strip() if (input_pass==rows[1][2]): box.addstr(height-4,0,club_prompt) screen.refresh() box.refresh() x=0 while x!=ord('\n'): #x = screen.getch() x = ugetch(screen) if ((x>=ord("0") and x<=ord("9"))): allowed_club+=chr(x) box.addstr(height-4,0,club_prompt+allowed_club) screen.refresh() box.refresh() allowed_club=allowed_club.strip() conyxDBGenDML('update config set value = "%s" where key="rodicovsky_zamek_klub"' % allowed_club) box.addstr(height-2,0,"*** RODIC SCHVALIL KLUB *** "+str(allowed_club), highlightText ) conyxDBLast(allowed_club) else: box.addstr(height-4,0,"ZADANO HESLO NESOUHLASI") if (x==ord("3")): rows=getConfig("barvicky") colors_allowed_comment="" if (rows[0][0]=='A'): colors_allowed_comment="NE" colors_allowed='N' else: colors_allowed_comment="ANO" colors_allowed='A' updateConfig("barvicky",colors_allowed) box.addstr(height-3,0,"UPRAVENA KONFIGURACE ZOBRAZENI BAREV NA %s" % colors_allowed_comment) if (x==ord("4")): upload_prompt="ZADEJ ZDROJOVY ADRESAR PRO ODESILANE SOUBORY: " rows=getConfig("soubory") upload_dir=str(getConfig('soubory')[0][0]) box.addstr(height-4,0,upload_prompt+" "+upload_dir) screen.refresh() box.refresh() x=0 while x!=ord('\n'): x = ugetch(screen) if x in (curses.KEY_BACKSPACE,263,127): if len(upload_dir)>0: upload_dir=upload_dir[:-1] box.addstr(height-4,0,upload_prompt+(" "*(width-1))) box.addstr(height-4,0,upload_prompt+" "+upload_dir) else: upload_dir+=chr(x) box.addstr(height-4,0,upload_prompt+" "+upload_dir) screen.refresh() box.refresh() upload_dir=upload_dir.strip() conyxDBGenDML('update config set value = "%s" where key="soubory"' % upload_dir) box.addstr(height-2,0,"*** NASTAVEN ADRESAR PRO ODESILANE SOUBORY *** "+str(upload_dir), highlightText ) screen.refresh() box.refresh() x = screen.getch() curses.endwin()
endwin() game_play() if robot.decodes == 5 and robot.flag1==1: #stopgame=False win = newwin(30,80,2,30) win.border(124,124,45,45,'*','*','*','*') win.addstr(12,26,'!!!!!!YOU WON THE GAME WITH!!!!!!') win.addstr(13,25,'@@@@@YOU EARNED -> ' +str(robot.points)+' POINTS@@@@@') win.addstr(14,23,'~~~PRESS n TO ENTER THE SECOND LEVEL~~~') win.addstr(15,24,'>>>PRESS Esc KEY TO QUIT FROM GAME<<<') while(1): key = win.getch() noecho() if key == 27 or key == ord('n'): break if key == 27: endwin() if key == ord('n'): endwin() import secondlevel else: win = newwin(30,80,2,30) win.border(124,124,45,45,'*','*','*','*') win.addstr(12,25,'!!!!!!YOU LOSE THE GAME!!!!!!') win.addstr(13,26,'@@@@YOU EARNED -> ' +str(robot.points)+' POINTS@@@@') win.addstr(14,24,'>>>PRESS Esc KEY TO QUIT FROM GAME<<<') while(win.getch()!=27): continue endwin()
def send_kill(self, signum, fram): self.player.stop() self.cache.quit() self.storage.save() curses.endwin() sys.exit()
def exit(self): self.screen.clear() self.screen.keypad(0) curses.echo() curses.nocbreak() curses.endwin()
def quitGame(score): record(score) scoreboard(score) curses.endwin() os.system("pycurses.py") quit()
def start(self): self.fifo.start() self.menu_starts = time.time() self.ui.build_menu( self.datatype, self.title, self.datalist, self.offset, self.index, self.step, self.menu_starts, ) self.stack.append( [self.datatype, self.title, self.datalist, self.offset, self.index] ) show_lyrics_new_process() while True: datatype = self.datatype title = self.title datalist = self.datalist offset = self.offset idx = self.index step = self.step self.screen.timeout(500) key = self.screen.getch() self.ui.screen.refresh() fifo = self.fifo.retrieve() # term resize if key == -1: self.player.update_size() if self.is_in_countdown: if time.time() - self.countdown_start > self.countdown: key = ord("q") # 退出 if key == ord("q"): break # 退出并清除用户信息 if key == ord("w"): self.api.logout() break # 上移 elif key == ord("k"): # turn page if at beginning if idx == offset: if offset == 0: continue self.offset -= step # 移动光标到最后一列 self.index = offset - 1 else: self.index = carousel( offset, min(len(datalist), offset + step) - 1, idx - 1 ) self.menu_starts = time.time() # 下移 elif key == ord("j"): # turn page if at end if idx == min(len(datalist), offset + step) - 1: if offset + step >= len(datalist): continue self.offset += step # 移动光标到第一列 self.index = offset + step else: self.index = carousel( offset, min(len(datalist), offset + step) - 1, idx + 1 ) self.menu_starts = time.time() # 数字快捷键 elif ord("0") <= key <= ord("9"): idx = key - ord("0") self.ui.build_menu( self.datatype, self.title, self.datalist, self.offset, idx, self.step, self.menu_starts, ) self.ui.build_loading() self.dispatch_enter(idx) self.index = 0 self.offset = 0 # 向上翻页 elif key == ord("u"): if offset == 0: continue self.menu_starts = time.time() self.offset -= step # e.g. 23 - 10 = 13 --> 10 self.index = (self.index - step) // step * step # 向下翻页 elif key == ord("d"): if offset + step >= len(datalist): continue self.menu_starts = time.time() self.offset += step # e.g. 23 + 10 = 33 --> 30 self.index = (self.index + step) // step * step # 前进 elif key == ord("l") or key == 10: self.enter_flag = True if len(self.datalist) <= 0: continue self.menu_starts = time.time() self.ui.build_loading() self.dispatch_enter(idx) if self.enter_flag is True: self.index = 0 self.offset = 0 # 回退 elif key == ord("h"): # if not main menu if len(self.stack) == 1: continue self.menu_starts = time.time() up = self.stack.pop() self.datatype = up[0] self.title = up[1] self.datalist = up[2] self.offset = up[3] self.index = up[4] self.at_playing_list = False # 搜索 elif key == ord("f"): # 8 is the 'search' menu self.dispatch_enter(8) # 播放下一曲 elif key == ord("]"): self.next_song() elif fifo == "next": self.next_song() # 播放上一曲 elif key == ord("["): self.previous_song() elif fifo == "prev": self.previous_song() # 增加音量 elif key == ord("="): self.player.volume_up() # 减少音量 elif key == ord("-"): self.player.volume_down() # 随机播放 elif key == ord("?"): if len(self.player.info["player_list"]) == 0: continue self.player.shuffle() # 喜爱 elif key == ord(","): return_data = self.request_api(self.api.fm_like, self.player.playing_id) if return_data: song_name = self.player.playing_name notify("%s added successfully!" % song_name, 0) else: notify("Adding song failed!", 0) # 删除FM elif key == ord("."): if self.datatype == "fmsongs": if len(self.player.info["player_list"]) == 0: continue self.player.next() return_data = self.request_api( self.api.fm_trash, self.player.playing_id ) if return_data: notify("Deleted successfully!", 0) # 下一FM elif key == ord("/"): if self.datatype == "fmsongs": if len(self.player.info["player_list"]) == 0: continue if self.player.end_callback: self.player.end_callback() # 播放、暂停 elif key == ord(" "): if not self.datalist: continue if idx < 0 or idx >= len(self.datalist): self.player.info["idx"] = 0 # If change to a new playing list. Add playing list and play. if datatype == "songs": self.player.new_player_list("songs", self.title, self.datalist, -1) self.player.end_callback = None self.player.play_or_pause(idx, self.at_playing_list) self.at_playing_list = True elif datatype == "djchannels": self.player.new_player_list( "djchannels", self.title, self.datalist, -1 ) self.player.end_callback = None self.player.play_or_pause(idx, self.at_playing_list) self.at_playing_list = True elif datatype == "fmsongs": self.player.change_mode(0) self.player.new_player_list( "fmsongs", self.title, self.datalist, -1 ) self.player.end_callback = self.fm_callback self.player.play_or_pause(idx, self.at_playing_list) self.at_playing_list = True else: # 所在列表类型不是歌曲 isNotSongs = True self.player.play_or_pause(self.player.info["idx"], isNotSongs) # 加载当前播放列表 elif key == ord("p"): self.show_playing_song() # 播放模式切换 elif key == ord("P"): self.player.change_mode() # 进入专辑 elif key == ord("A"): if datatype == "album": continue if datatype in ["songs", "fmsongs"]: song_id = datalist[idx]["song_id"] album_id = datalist[idx]["album_id"] album_name = datalist[idx]["album_name"] elif self.player.playing_flag: song_id = self.player.playing_id song_info = self.player.songs.get(str(song_id), {}) album_id = song_info.get("album_id", "") album_name = song_info.get("album_name", "") else: album_id = 0 if album_id: self.stack.append([datatype, title, datalist, offset, self.index]) songs = self.api.album(album_id) self.datatype = "songs" self.datalist = self.api.dig_info(songs, "songs") self.title = "网易云音乐 > 专辑 > %s" % album_name for i in range(len(self.datalist)): if self.datalist[i]["song_id"] == song_id: self.offset = i - i % step self.index = i break # 添加到打碟歌单 elif key == ord("a"): if datatype == "songs" and len(datalist) != 0: self.djstack.append(datalist[idx]) elif datatype == "artists": pass # 加载打碟歌单 elif key == ord("z"): self.stack.append([datatype, title, datalist, offset, self.index]) self.datatype = "songs" self.title = "网易云音乐 > 打碟" self.datalist = self.djstack self.offset = 0 self.index = 0 # 添加到本地收藏 elif key == ord("s"): if (datatype == "songs" or datatype == "djchannels") and len( datalist ) != 0: self.collection.append(datalist[idx]) notify("Added successfully", 0) # 加载本地收藏 elif key == ord("c"): self.stack.append([datatype, title, datalist, offset, self.index]) self.datatype = "songs" self.title = "网易云音乐 > 本地收藏" self.datalist = self.collection self.offset = 0 self.index = 0 # 从当前列表移除 elif key == ord("r"): if ( datatype in ("songs", "djchannels", "fmsongs") and len(datalist) != 0 ): self.datalist.pop(idx) self.index = carousel( offset, min(len(datalist), offset + step) - 1, idx ) elif key == ord("t"): self.countdown_start = time.time() countdown = self.ui.build_timing() if not countdown.isdigit(): notify("The input should be digit") continue countdown = int(countdown) if countdown > 0: notify("The musicbox will exit in {} minutes".format(countdown)) self.countdown = countdown * 60 self.is_in_countdown = True else: notify("The timing exit has been canceled") self.is_in_countdown = False # 当前项目下移 elif key == ord("J"): if ( datatype != "main" and len(datalist) != 0 and idx + 1 != len(self.datalist) ): self.menu_starts = time.time() song = self.datalist.pop(idx) self.datalist.insert(idx + 1, song) self.index = idx + 1 # 翻页 if self.index >= offset + step: self.offset = offset + step # 当前项目上移 elif key == ord("K"): if datatype != "main" and len(datalist) != 0 and idx != 0: self.menu_starts = time.time() song = self.datalist.pop(idx) self.datalist.insert(idx - 1, song) self.index = idx - 1 # 翻页 if self.index < offset: self.offset = offset - step elif key == ord("m"): if datatype != "main": self.stack.append([datatype, title, datalist, offset, self.index]) self.datatype = self.stack[0][0] self.title = self.stack[0][1] self.datalist = self.stack[0][2] self.offset = 0 self.index = 0 elif key == ord("g"): if datatype == "help": webbrowser.open_new_tab("https://github.com/darknessomi/musicbox") else: self.index = 0 self.offset = 0 elif key == ord("G"): self.index = len(self.datalist) - 1 self.offset = self.index - self.index % step # 开始下载 elif key == ord("C"): s = self.datalist[idx] cache_thread = threading.Thread( target=self.player.cache_song, args=(s["song_id"], s["song_name"], s["artist"], s["mp3_url"]), ) cache_thread.start() elif key == ord("i"): if self.player.playing_id != -1: webbrowser.open_new_tab( "http://music.163.com/song?id={}".format(self.player.playing_id) ) self.ui.build_process_bar( self.player.current_song, self.player.process_location, self.player.process_length, self.player.playing_flag, self.player.info["playing_mode"], ) self.ui.build_menu( self.datatype, self.title, self.datalist, self.offset, self.index, self.step, self.menu_starts, ) self.player.stop() self.cache.quit() self.storage.save() curses.endwin()
def main(speed, level): flag = 0 #To see if game is paused or not lost = 0 #To see if the user loses or not count = 0 #count of the diffuse kits obtained ret = -2 # global x ; global y xnew = box.x ynew = box.y #Make safe copies of x, y win = addscreen() #adds the window definecolors() #colors initialised bullet = 0 #bullet position # bkgcolor(win) addelements(win, level) #adds robot(s),mines, diffuse codes, bomb event = ord("q") while (event != 27): win.addstr(0, 2, ' Diffuse Codes: ' + str(count) + ' ') win.addstr(box.height - 1, box.x - 4, 'Level: ' + str(level) + ' ') win.timeout( speed - 15 * count) #As robot takes diffuse codes, its speed increases key = win.getch() if (key == 27): break if (flag == 0): if (key == ord("p") or key == ord("P")): #If paused flag = 1 win.addstr(0, box.x, ' Paused!') resume = event else: if (key == -1 or (key != KEY_RIGHT and key != KEY_LEFT and key != KEY_UP and key != KEY_DOWN)): event = event else: event = key elif (flag == 1): if (key == ord("p") or key == ord("P") ): #Resume the previous state after p is pressed again flag = 0 event = resume win.box() if (event == KEY_RIGHT and flag == 0): #If robot moved right if (xnew + 2 < box.width - 2 and flag == 0): #If robot inside boundary for i in range(ynew - 2, ynew + 2): #To check the neighbouring characteres ch = win.inch(i, xnew + 3) ret = check(count, ch) if (ret >= count): count = ret elif (ret == -2): #Hits the wall lost = 1 break elif (ret == -1): #Hits the bomb break if (ret == -1 or ret == -2): break xnew = xnew + 1 #update new coordinates drawrobot(win, ynew - 2, xnew - 2) #Draw the new robot win.addch(ynew - 2, xnew - 3, ' ') #Delete the previous robot win.addch(ynew - 1, xnew - 3, ' ') win.addch(ynew, xnew - 3, ' ') win.addch(ynew + 1, xnew - 3, ' ') elif (xnew + 2 == box.width - 2): #see if robo hits the wall lost = 1 #user loses break if (event == KEY_LEFT and flag == 0): if (xnew - 2 > 1): for i in range(ynew - 2, ynew + 2): ch = win.inch(i, xnew - 3) ret = check(count, ch) if (ret >= count): count = ret elif (ret == -2): lost = 1 break elif (ret == -1): break if (ret == -1 or ret == -2): break xnew = xnew - 1 drawrobot(win, ynew - 2, xnew - 2) win.addch(ynew - 2, xnew + 3, ' ') win.addch(ynew - 1, xnew + 3, ' ') win.addch(ynew, xnew + 3, ' ') win.addch(ynew + 1, xnew + 3, ' ') elif (xnew - 2 == 1): lost = 1 break if (event == KEY_UP and flag == 0): if (ynew - 2 > 1): for i in range(xnew - 2, xnew + 3): ch = win.inch(ynew - 3, i) ret = check(count, ch) if (ret >= count): count = ret elif (ret == -2): lost = 1 break elif (ret == -1): break if (ret == -1 or ret == -2): break ynew = ynew - 1 drawrobot(win, ynew - 2, xnew - 2) win.addch(ynew + 2, xnew - 2, ' ') win.addch(ynew + 2, xnew - 1, ' ') win.addch(ynew + 2, xnew, ' ') win.addch(ynew + 2, xnew + 1, ' ') win.addch(ynew + 2, xnew + 2, ' ') elif (ynew - 2 == 1): lost = 1 break if (event == KEY_DOWN and flag == 0): if (ynew + 1 < box.height - 2 and flag == 0): for i in range(xnew - 2, xnew + 3): ch = win.inch(ynew + 2, i) ret = check(count, ch) if (ret >= count): count = ret elif (ret == -2): lost = 1 break elif (ret == -1): break if (ret == -1 or ret == -2): break ynew = ynew + 1 drawrobot(win, ynew - 2, xnew - 2) win.addch(ynew - 3, xnew - 2, ' ') win.addch(ynew - 3, xnew - 1, ' ') win.addch(ynew - 3, xnew, ' ') win.addch(ynew - 3, xnew + 1, ' ') win.addch(ynew - 3, xnew + 2, ' ') elif (ynew + 1 == box.height - 2): lost = 1 break if (level >= 2 and flag == 0 ): #move the bullet forward and see if it hits the bullet win.addch(box.height / 3 - 1, 7 + (bullet), ' ') #1 win.addch(2 * box.height / 3 - 1, box.width - (7 + (bullet)), ' ') bullet = (bullet + 1) % (box.width - 8) #2 ch = win.inch(box.height / 3 - 1, 7 + bullet) #3 if (ch != ord(" ")): #4 lost = 1 #5 break #6 win.addch(box.height / 3 - 1, 7 + (bullet), '-') #7 ch = win.inch(2 * box.height / 3 - 1, box.width - (7 + bullet)) if (ch != ord(" ")): lost = 1 break win.addch(2 * box.height / 3 - 1, box.width - (7 + (bullet)), '-') curses.endwin() if (count != box.d): lost = 1 return lost
def main(stdscr_): std_scr = curses.initscr() curses.curs_set(0) console_height, console_width = std_scr.getmaxyx() screen = curses.newwin(console_height, console_width, 0, 0) screen.keypad(1) screen.timeout(100) # Snake snk_x = console_width // 4 snk_y = console_height // 2 snake = [[snk_y, snk_x], [snk_y, snk_x - 1], [snk_y, snk_x - 2]] # Display first food in the center food = [console_height // 2, console_width // 2] screen.addch(food[0], food[1], curses.ACS_PI) # Start by going right key = curses.KEY_RIGHT while True: next_key = screen.getch() key = key if next_key == -1 else next_key # Collision if snake[0][0] in [0, console_height] or snake[0][1] in [ 0, console_width ] or snake[0] in snake[1:]: curses.endwin() quit() new_head = [snake[0][0], snake[0][1]] # Event listening if key == curses.KEY_DOWN: new_head[0] += 1 if key == curses.KEY_UP: new_head[0] -= 1 if key == curses.KEY_LEFT: new_head[1] -= 1 if key == curses.KEY_RIGHT: new_head[1] += 1 snake.insert(0, new_head) # Eating food if snake[0] == food: food = None while food is None: new_food = [ random.randint(1, console_height - 1), random.randint(1, console_width - 1) ] food = new_food if new_food not in snake else None screen.addch(food[0], food[1], curses.ACS_PI) else: tail = snake.pop() screen.addch(tail[0], tail[1], ' ') screen.addch(snake[0][0], snake[0][1], curses.ACS_CKBOARD)
def __del__(self): """ Reset the console.""" self.configure() curses.endwin()
def run(): score = 0 level = 1 levels = 10 lost = main(100, level) while (level < levels): if lost == 0: score = score + box.s box.s += 5 nxt = result(lost) if (nxt == 'y'): level += 1 lost = main(180 - 20 * level, level) elif (nxt == 'n'): win = addscreen() definecolors() win.addstr(box.y - 1, box.x - 10, 'Your final score : ' + str(score) + ' ', curses.color_pair(3)) win.addstr(box.y + 2, box.x - 10, 'Press ESC to exit', curses.color_pair(3)) while (1): key = win.getch() if (key == 27): break curses.endwin() break elif (lost == 1): win = addscreen() definecolors() win.addstr(box.y - 2, box.x - 5, "You LOST!", curses.color_pair(3)) win.addstr(box.y, box.x - 10, 'Your final score is ' + str(score) + ' ', curses.color_pair(3)) win.addstr(box.y + 2, box.x - 8, 'Press ESC to exit', curses.color_pair(3)) while (1): key = win.getch() if (key == 27): break curses.endwin() break if (level == levels and lost == 0): win = addscreen() definecolors() win.addstr(box.y - 2, box.x - 10, "You completed all levels!!!", curses.color_pair(2)) win.addstr(box.y, box.x - 10, 'Your final score is ' + str(score) + ' ', curses.color_pair(2)) win.addstr(box.y + 2, box.x - 10, 'Thanks for playing!', curses.color_pair(2)) win.addstr(box.y + 4, box.x - 10, 'Press ESC to exit', curses.color_pair(2)) while (1): key = win.getch() if (key == 27): break curses.endwin() if (level == levels and lost == 1): win = addscreen() definecolors() win.addstr(box.y - 2, box.x - 5, "You LOST!", curses.color_pair(3)) win.addstr(box.y, box.x - 10, 'Your final score is ' + str(score) + ' ', curses.color_pair(3)) while (1): key = win.getch() if (key == 27): break curses.endwin()
def exitCurses(): curses.nocbreak() window.keypad(False) curses.echo() curses.endwin()
def __del__(self): print ("destructor") # shut down curses cleanly curses.nocbreak(); self.stdscr.keypad(0); curses.echo() curses.endwin()
"""curses.wrapper
else: if playerchoice == win_against(aichoice): stdscr.addstr(7, 0, "AI wins", flashnum) playerhp -= 1 else: stdscr.addstr(7, 0, "Player wins", flashnum) aihp -= 1 if flashnum == c.A_NORMAL: flashnum = c.A_REVERSE else: flashnum = c.A_NORMAL elif k == ord("q"): exitcode = 0 break if exitcode == 1: stdscr.addstr(9, 0, "You died", c.A_BOLD | c.A_UNDERLINE) stdscr.getch() elif exitcode == 2: stdscr.addstr(9, 0, "You killed the AI", c.A_BOLD | c.A_UNDERLINE) stdscr.getch() elif exitcode == 0: pass finally: c.noraw() c.cbreak() c.echo() stdscr.keypad(False) c.endwin()
def closeCurses(stdscr): stdscr.keypad(0) curses.echo() curses.endwin()
def main(args): hostname = socket.gethostname() blockList = get_transmit_receive() order = sorted([blockList[key]['pid'] for key in blockList]) order = set(order) nPID = len(order) scr = curses.initscr() curses.noecho() curses.cbreak() scr.keypad(1) scr.nodelay(1) size = scr.getmaxyx() std = curses.A_NORMAL rev = curses.A_REVERSE poll_interval = 1.0 tLastPoll = 0.0 try: sel = 0 while True: t = time.time() ## Interact with the user c = scr.getch() curses.flushinp() if c == ord('q'): break elif c == curses.KEY_UP: sel -= 1 elif c == curses.KEY_DOWN: sel += 1 ## Find the current selected process and see if it has changed newSel = min([nPID - 1, max([0, sel])]) if newSel != sel: tLastPoll = 0.0 sel = newSel ## Do we need to poll the system again? if t - tLastPoll > poll_interval: ## Save what we had before prevList = blockList ## Find all running processes pidDirs = glob.glob(os.path.join(BIFROST_STATS_BASE_DIR, '*')) pidDirs.sort() ## Load the data blockList = get_transmit_receive() ## Sort order = sorted([blockList[key]['pid'] for key in blockList]) order = list(set(order)) nPID = len(order) ## Stats stats = get_statistics(blockList, prevList) ## Mark tLastPoll = time.time() ## Clear act = None ## For sel to be valid - this takes care of any changes between when ## we get what to select and when we polled the bifrost logs sel = min([nPID - 1, sel]) ## Deal with more pipelines than there is screen space by skipping ## over some at the beginning of the list to_skip = 0 if sel > size[0] - 13: to_skip = sel - size[0] + 13 ## Display k = 0 ### General - selected try: output = ' PID: %i on %s' % (order[sel], hostname) except IndexError: output = ' PID: n/a on %s' % (hostname, ) output += ' ' * (size[1] - len(output) - len(os.path.basename(__file__)) - 1) output += os.path.basename(__file__) + ' ' output += '\n' k = _add_line(scr, k, 0, output, std) ### General - header k = _add_line(scr, k, 0, ' ', std) output = '%6s %9s %6s %9s %6s' % ( 'PID', 'RX Rate', 'RX #/s', 'TX Rate', 'TX #/s') output += ' ' * (size[1] - len(output)) output += '\n' k = _add_line(scr, k, 0, output, rev) ### Data for i, o in enumerate(order): if i < to_skip: continue curr = stats[o] if o == order[sel]: act = curr drateR, prateR = curr['rx']['drate'], curr['rx']['prate'] drateR, drateuR = _set_units(drateR) drateT, prateT = curr['tx']['drate'], curr['tx']['prate'] drateT, drateuT = _set_units(drateT) output = '%6i %7.2f%2s %6i %7.2f%2s %6i\n' % ( o, drateR, drateuR, prateR, drateT, drateuT, prateT) try: if o == order[sel]: sty = std | curses.A_BOLD else: sty = std except IndexError: sty = std k = _add_line(scr, k, 0, output, sty) if k > size[0] - 10: break while k < size[0] - 9: output = ' ' k = _add_line(scr, k, 0, output, std) ### Details of selected output = 'Details - %8s %19s %19s' % ( stats['updated'].strftime("%H:%M:%S"), 'RX', 'TX') output += ' ' * (size[1] - len(output)) output += '\n' k = _add_line(scr, k, 0, output, rev) if act is not None: output = 'Good: %18iB %18iB\n' % ( act['rx']['good'], act['tx']['good']) k = _add_line(scr, k, 0, output, std) output = 'Missing: %18iB %18iB\n' % ( act['rx']['missing'], act['tx']['missing']) k = _add_line(scr, k, 0, output, std) output = 'Invalid: %18iB %18iB\n' % ( act['rx']['invalid'], act['tx']['invalid']) k = _add_line(scr, k, 0, output, std) output = 'Late: %18iB %18iB\n' % ( act['rx']['late'], act['tx']['late']) k = _add_line(scr, k, 0, output, std) output = 'Global Missing: %18.2f%% %18.2f%%\n' % ( act['rx']['gloss'], act['tx']['gloss']) k = _add_line(scr, k, 0, output, std) output = 'Current Missing: %18.2f%% %18.2f%%\n' % ( act['rx']['closs'], act['tx']['closs']) k = _add_line(scr, k, 0, output, std) output = 'Command: %s' % act['cmd'] k = _add_line(scr, k, 0, output[:size[1]], std) ### Clear to the bottom scr.clrtobot() ### Refresh scr.refresh() ## Sleep time.sleep(_REDRAW_INTERVAL_SEC) except KeyboardInterrupt: pass except Exception as error: exc_type, exc_value, exc_traceback = sys.exc_info() fileObject = StringIO() traceback.print_tb(exc_traceback, file=fileObject) tbString = fileObject.getvalue() fileObject.close() scr.keypad(0) curses.echo() curses.nocbreak() curses.endwin() try: print( "%s: failed with %s at line %i" % (os.path.basename(__file__), str(error), exc_traceback.tb_lineno)) for line in tbString.split('\n'): print(line) except NameError: pass
def stop(self): self.is_stop = True curses.endwin() print('stopped')
def main(): stdscr = curses.initscr() curses.cbreak() curses.curs_set(0) stdscr.keypad(1) stdscr.timeout(100) snake = Snake() alive = True while alive: stdscr.refresh() stdscr.clear() for i in range(0, curses.COLS): stdscr.addstr(0, i, "=") stdscr.addstr(curses.LINES - 2, i, "=") for j in range(0, curses.LINES): stdscr.addstr(j, 0, "+") stdscr.addstr(j, curses.COLS - 2, "+") for opp, bd in opponents.items( ): #opponents includes rendering me as well if bd == []: continue #Could add collision with other check here. Check if my head == other posision (o_x, o_y) = bd[0] stdscr.addstr(o_y, o_x, "@") for (x, y) in bd[1:]: stdscr.addstr(y, x, "#") key = stdscr.getch() if key == curses.KEY_DOWN: snake.vx = 0 snake.vy = 1 elif key == curses.KEY_UP: snake.vx = 0 snake.vy = -1 elif key == curses.KEY_LEFT: snake.vx = -1 snake.vy = 0 elif key == curses.KEY_RIGHT: snake.vx = 1 snake.vy = 0 alive = snake.checkAlive() snake.updatePos() global body body = snake.getBody() time.sleep(sleeptime) curses.endwin() global done done = True
def dialogues(text, time): screen.erase() screen.border() lines = curses.LINES cols = curses.COLS col = 1 line = 2 counter = 0 counter_line = 0 num = 0 x = '' paso = False for i in list(text): screen.refresh() counter += 1 if counter > (cols - 6): counter = 0 counter_line += 1 line += 1 col = 2 else: col += 1 if i == '\n': line += 1 col = 1 counter = 0 counter_line += 1 if counter_line > (lines - 6): counter_line = 0 screen.move(line + 1, cols - len('Suguiente...') - 1) screen.addstr('Siguiente...') screen.getch() screen.erase() screen.border() col = 2 line = 2 if (col + len(x)) > (cols - 3): screen.move(line, col + 1) screen.addstr('-') screen.getch() line += 1 col = 2 counter = 0 screen.move(line, col) screen.addstr(i) curses.napms(time) screen.refresh() screen.border() screen.move(lines - 2, cols - len('Continuar...') - 1) screen.addstr('Continuar...') screen.getch() curses.endwin() return lines, cols, x
def __del__(self): self.win.keypad(False) curses.nocbreak() curses.echo() curses.endwin()
def __quit(self, command, win_index=0): curses.endwin() os._exit(0)
def _end_screen(self): curses.endwin()
def main(screen): curses.curs_set(0) screen_height, screen_width = screen.getmaxyx() window = curses.newwin(screen_height, screen_width, 0, 0) window.timeout(100) window.keypad(1) snake_x = screen_width / 2 snake_y = screen_height / 2 snake = [ [snake_x, snake_y], [snake_x, snake_y - 1], [snake_x, snake_y - 2], ] window.addch(int(snake[0][1]), int(snake[0][0]), curses.ACS_CKBOARD) food = [screen_width / 4, screen_height / 2] window.addch(int(food[1]), int(food[0]), curses.ACS_PI) key = curses.KEY_RIGHT past_key = curses.KEY_LEFT while True: next_key = window.getch() key = key if next_key == -1 else next_key if key == past_key and past_key == curses.KEY_LEFT: key = curses.KEY_RIGHT if key == past_key and past_key == curses.KEY_RIGHT: key = curses.KEY_LEFT if key == past_key and past_key == curses.KEY_UP: key = curses.KEY_DOWN if key == past_key and past_key == curses.KEY_DOWN: key = curses.KEY_UP if snake[0][0] in [0, screen_width] or snake[0][1] in [ 0, screen_height ] or snake[0] in snake[1:]: curses.endwin() quit() head = [snake[0][0], snake[0][1]] # TODO: check does not change to direction it is moving from if key == curses.KEY_LEFT: head[0] -= 1 past_key = curses.KEY_RIGHT if key == curses.KEY_RIGHT: head[0] += 1 past_key = curses.KEY_LEFT if key == curses.KEY_UP: head[1] -= 1 past_key = curses.KEY_DOWN if key == curses.KEY_DOWN: head[1] += 1 past_key = curses.KEY_UP snake.insert(0, head) if snake[0] == food: food = None while food is None: new_food = [ random.randint(1, screen_width - 1), random.randint(1, screen_height - 1) ] food = new_food if new_food not in snake else None window.addch(food[1], food[0], curses.ACS_PI) else: tail = snake.pop() window.addch(int(tail[1]), int(tail[0]), ' ') window.addch(int(snake[0][1]), int(snake[0][0]), curses.ACS_CKBOARD)
def shutdown(self): self.message("", "\n", "") self.miner.logqueue.join() curses.endwin()