def __init__(self): self.input_string = "" self.all_entries = get_entries_from_file() self.matches = [] self.selected_option_index = 0 self.screen = curses.initscr() self.screen.clear() # signal.signal(signal.SIGINT, lambda signum, frame: None) self.screen.keypad(True) curses.raw() curses.noecho() curses.cbreak() curses.nonl() curses.start_color() curses.init_pair(1, curses.COLOR_YELLOW, curses.COLOR_BLACK) curses.init_pair(2, curses.COLOR_YELLOW, curses.COLOR_MAGENTA) curses.newwin(0, 0) self.screen.keypad(1) self.screen.addstr(0, 0, "QUERY>") try: self.process_new_input() while True: pressed_key = self.screen.getch() self._handle_keypress(pressed_key) self.process_new_input() except: #TODO: maybe catch only keyboard interrupt???? curses.nocbreak() self.screen.keypad(False) curses.echo() curses.nl() curses.endwin()
def destroy(self): curses.nocbreak() self.stdscr.keypad(0) curses.nl() curses.curs_set(1) curses.echo() curses.endwin()
def _handle_keypress(self, pressed_key): if pressed_key == 8 or pressed_key == 127 or pressed_key == curses.KEY_BACKSPACE: self.input_string = self.input_string[:-1] elif pressed_key == curses.KEY_ENTER or pressed_key == 10 or pressed_key == 13: final_output = self.matches[self.selected_option_index][1] curses.nocbreak() self.screen.keypad(False) curses.echo() curses.nl() curses.endwin() sys.stdout.flush() sys.stdout.buffer.write(final_output.encode('utf-8')) sys.stdout.buffer.write(b"\n") sys.stdout.flush() sys.exit() elif pressed_key == curses.KEY_DOWN: screen_vertical_real_estate = self._get_vertical_real_estate() if self.selected_option_index < screen_vertical_real_estate - 1: self.selected_option_index += 1 elif pressed_key == curses.KEY_UP: if self.selected_option_index > 0: self.selected_option_index -= 1 elif curses.ascii.isprint( pressed_key): # this also needs to be replaced by something. x, y = curses.getsyx() self.input_string = self.input_string + str(chr(pressed_key)) self.selected_option_index = 0
def int16(self): ah = self.ql.reg.ah if ah == 0x0: curses.nonl() key = self._parse_key(self.stdscr.getch()) self.ql.dprint(0, f"Get key: {hex(key)}") if curses.ascii.isascii(key): self.ql.reg.al = key else: self.ql.reg.al = 0 self.ql.reg.ah = self._get_scan_code(key) curses.nl() elif ah == 0x1: curses.nonl() # set non-blocking self.stdscr.timeout(0) key = self._parse_key(self.stdscr.getch()) if key == -1: self.set_flag(0x40) self.ql.reg.ax = 0 else: self.ql.dprint(0, f"Has key: {hex(key)} ({curses.ascii.unctrl(key)})") self.ql.reg.al = key self.ql.reg.ah = self._get_scan_code(key) self.clear_flag(0x40) # Buffer shouldn't be removed in this interrupt. curses.ungetch(key) self.stdscr.timeout(-1) curses.nl()
def __init__(self, width, height, exception_if_overprinted, delay_after_each_step, inside_unit_test): super().__init__() self.inside_unit_test = inside_unit_test # if your program fails here, add environment variable TERM=linux self.stdscr = curses.initscr() if inside_unit_test: self.stdscr.clear() self._resize_if_more_space_is_needed(height, width) # no enter key needed to post input; # can be disabled, it caused error when running print-out-only tests if not self.inside_unit_test: curses.cbreak() curses.nl() # escape sequences (numpad, function keys, ...) will be interpreted self.stdscr.keypad(True) self.stdscr.move(0, 0) self.width = width self.height = height self.canvas = [] for y in range(height): new_list = [] for x in range(width): new_list.append(" ") self.canvas.append(new_list) self.canvas_x = 0 self.canvas_y = 0 self.exception_if_overprinted = exception_if_overprinted self.delay_after_each_step = delay_after_each_step
def uninit_rt(): curses.nocbreak() curses.echo() curses.nl() curses.intrflush(1) curses.endwin() exit()
def main(window, pattern): curses.nl() curses.noecho() window.timeout(0) current_direction, cur_point = reset_window(window) index = 0 while True: if index == len(pattern): index = 0 direction = get_new_direction(current_direction, pattern[index]) try: cur_point = draw_line(window, cur_point, direction, current_direction) current_direction = direction index += 1 except OutOfBoundsError: current_direction, cur_point = reset_window(window) ch = window.getch() if ch == ord('q') or ch == ord('Q'): return elif ch == ord('s'): # for debugging allow us to step through program window.nodelay(0) elif ch == ord(' '): window.nodelay(1) curses.napms(100)
def close(self): curses.nocbreak() curses.curs_set(1) self.window.keypad(0) curses.nl() curses.echo() curses.endwin()
def main(win): global stdscr stdscr = win if curses.has_colors(): bg = curses.COLOR_BLACK curses.init_pair(1, curses.COLOR_BLUE, bg) curses.init_pair(2, curses.COLOR_CYAN, bg) curses.nl() # new line curses.noecho() stdscr.timeout(0) x = 0 y = 0 while True: draw_map() stdscr.addch(y, x, ord("*")) y, x = auto_run(y, x) ch = stdscr.getch() if ch == ord("q") or ch == ord("Q"): return stdscr.erase() # erase and refresh should have a proper interval curses.napms(100) stdscr.refresh()
def _exit_curses(self): curses.curs_set(1) curses.echo() curses.nocbreak() curses.nl() self._stdscr.keypad(False) curses.endwin()
def close(self): """Restores terminal to default behaviour.""" curses.nocbreak() self.stdscr.keypad(False) curses.echo() curses.nl() curses.endwin()
def main(win): global stdscr stdscr = win # 判断终端是否可以显示颜色 if curses.has_colors(): bg = curses.COLOR_BLACK curses.init_pair(1, curses.COLOR_BLUE, bg) curses.init_pair(2, curses.COLOR_CYAN, bg) # 开启新行模式 curses.nl() # 关闭输入回显 curses.noecho() # 设置为非阻塞模式读取 stdscr.timeout(0) while True: # 显示房子 house() smoke() ch = stdscr.getch() if ch == ord('q') or ch == ord('Q'): return elif ch == ord('s'): # 部进显示 stdscr.nodelay(0) elif ch == ord(' '): # 非延迟显示 stdscr.nodelay(1) # 睡眠50ms curses.napms(50)
def main(win): global stdscr stdscr = win if curses.has_colors(): bg = curses.COLOR_BLACK curses.init_pair(1, curses.COLOR_BLUE, bg) curses.init_pair(2, curses.COLOR_CYAN, bg) curses.nl() # new line curses.noecho() stdscr.timeout(0) x = 0 y = 0 while True: # We should get the border of screen max_y, max_x = stdscr.getmaxyx() draw_map() stdscr.addch(y, x, ord('*')) ch = stdscr.getch() if ch == ord('q') or ch == ord('Q'): return # I think we should do collision check when people # press the key elif ch == curses.KEY_DOWN: y += 1 if (y > max_y - 1): y = max_y - 1 elif collision_check(y, x): y -= 1 stdscr.erase() elif ch == curses.KEY_UP: y -= 1 if (y < 0): y = 0 elif collision_check(y, x): y += 1 stdscr.erase() elif ch == curses.KEY_RIGHT: x += 1 if (x > max_x - 1): x = max_x - 1 elif collision_check(y, x): x -= 1 stdscr.erase() elif ch == curses.KEY_LEFT: x -= 1 if (x < 0): x = 0 elif collision_check(y, x): x += 1 stdscr.erase() stdscr.refresh() curses.napms(10)
def init(stdscr): curses.curs_set(0) # get rid of cursor stdscr.clear() stdscr.refresh() curses.nl() curses.noecho() stdscr.timeout(0) stdscr.nodelay(0)
def __exit__(self, type, value, tb): # go to last line of screen, maybe cause scrolling? self.color_assigner.close() self.stdscr.keypad(0) curses.noraw() curses.nl() curses.echo() curses.endwin() signal.signal(signal.SIGTSTP, self.orig_sigtstp)
def ncurses(): """ Context manager for curses applications. This does a number of things beyond what curses.wrapper() does. - Redirect stdout to stderr. This is done so that we can still use the ncurses interface from within a pipe or subshell. - Drop the escape delay down to 25ms, similar to vim. - Remove newline mode. An ncurses screen is returned by the manager. If any exceptions occur, all of the setup performed by the manager is undone before raising the original exception. This should guarantee that any bugs in the code will not leave the user with a messed up shell. """ # Push stdout to stderr so that we still get the curses # output while inside of a pipe or subshell old_stdout = sys.__stdout__ old_stdout_fd = os.dup(sys.stdout.fileno()) os.dup2(sys.stderr.fileno(), sys.stdout.fileno()) # Reduce the timeout after receiving an escape character, there # doesn't seem to be a way to do this via curses so we have to # set the environment variable before creating the screen. if 'ESCDELAY' not in os.environ: os.environ['ESCDELAY'] = '25' scr = curses.initscr() curses.start_color() curses.use_default_colors() for i in range(curses.COLORS): curses.init_pair(i + 1, i, -1) curses.noecho() curses.cbreak() curses.raw() curses.nonl() curses.curs_set(2) scr.keypad(1) exc = None try: yield scr except Exception: exc = sys.exc_info() scr.keypad(0) curses.nl() curses.nocbreak() curses.echo() curses.endwin() os.dup2(old_stdout_fd, sys.stdout.fileno()) sys.stdout = old_stdout if exc is not None: exc[0].with_traceback(exc[1], exc[2])
def init(stdscr): stdscr.erase() curses.nl() curses.noecho() stdscr.timeout(0) stdscr.nodelay(0) stdscr.noutrefresh() curses.curs_set(0) curses.doupdate()
def ncurses(): """ Context manager for curses applications. This does a number of things beyond what curses.wrapper() does. - Redirect stdout to stderr. This is done so that we can still use the ncurses interface from within a pipe or subshell. - Drop the escape delay down to 25ms, similar to vim. - Remove newline mode. An ncurses screen is returned by the manager. If any exceptions occur, all of the setup performed by the manager is undone before raising the original exception. This should guarantee that any bugs in the code will not leave the user with a messed up shell. """ # Push stdout to stderr so that we still get the curses # output while inside of a pipe or subshell old_stdout = sys.__stdout__ old_stdout_fd = os.dup(sys.stdout.fileno()) os.dup2(sys.stderr.fileno(), sys.stdout.fileno()) # Reduce the timeout after receiving an escape character, there # doesn't seem to be a way to do this via curses so we have to # set the environment variable before creating the screen. if not 'ESCDELAY' in os.environ: os.environ['ESCDELAY'] = '25' scr = curses.initscr() curses.start_color() curses.use_default_colors() _ = [curses.init_pair(i + 1, i, -1) for i in range(curses.COLORS)] curses.noecho() curses.cbreak() curses.raw() curses.nonl() curses.curs_set(2) scr.keypad(1) exc = None try: yield scr #pylint: disable=W0703 except Exception: exc = sys.exc_info() scr.keypad(0) curses.nl() curses.nocbreak() curses.echo() curses.endwin() os.dup2(old_stdout_fd, sys.stdout.fileno()) sys.stdout = old_stdout if exc is not None: six.reraise(exc[0], exc[1], exc[2])
def __leaf_00(ql: Qiling): curses.nonl() key = parse_key(ql.os.stdscr.getch()) ql.log.debug(f"Get key: {hex(key)}") if curses.ascii.isascii(key): ql.arch.regs.al = key else: ql.arch.regs.al = 0 ql.arch.regs.ah = get_scan_code(key) curses.nl()
def _start_curses(self): # Initialize curses self.stdscr = curses.initscr() #curses.start_color() curses.noecho() curses.cbreak() curses.nl() curses.curs_set(0) self.stdscr.keypad(1) self.make_display() self.size = self._get_screen_size()
def stop(): global _screen if _screen: _screen.timeout(-1) _screen.keypad(0) _screen.scrollok(True) curses.nocbreak() curses.curs_set(1) curses.nl() curses.echo() curses.endwin() _screen = None
def stop(): global screen if screen: screen.timeout(-1) screen.keypad(0) screen.scrollok(True) curses.nocbreak() curses.curs_set(1) curses.nl() curses.echo() curses.endwin() screen = None
def _close(self): """Close the curses interface.""" # restore original terminal size if self.orig_size and console: self._resize(*self.orig_size) curses.noraw() curses.nl() curses.nocbreak() if self.screen: self.screen.keypad(False) curses.echo() curses.endwin()
def close(self): """ Close the text interface. """ video.VideoPlugin.close(self) if self.curses_init: # restore original terminal size self._resize(*self.orig_size) # restore sane terminal state curses.noraw() curses.nl() curses.nocbreak() self.screen.keypad(False) curses.echo() curses.endwin()
def __exit__(self, type, value, traceback): """Close the curses interface.""" base.VideoPlugin.__exit__(self, type, value, traceback) if self.curses_init: # restore original terminal size self._resize(*self.orig_size) # restore sane terminal state curses.noraw() curses.nl() curses.nocbreak() self.screen.keypad(False) curses.echo() curses.endwin()
def main(sc): curses.nl(); gameplay_window = curses.newwin(10, 30, 0, 0); map_window = curses.newwin(5, 10, 0, 35); stats_window = curses.newwin(5, 10, 5, 35); gameplay_window.keypad(True); curses.curs_set(0); player = player_.player((13, 4), (0, 0)); map = map_.map(5, 6); running = True; def render_all(): stats_window.clear(); map.rooms[player.room_y][player.room_x].render(gameplay_window) player.render(gameplay_window, stats_window); map.render(map_window, player); sc.refresh(); gameplay_window.refresh(); map_window.refresh(); stats_window.refresh(); render_all(); while running: key = gameplay_window.getkey(); if key == ' ': gameplay_window.addstr(2, 8, "Do you really"); gameplay_window.addstr(3, 5, "want to quit (y/n) ?"); gameplay_window.refresh(); k = gameplay_window.getkey(); if k == 'y': running = False; render_all(); continue; player.update(key); player = map.rooms[player.room_y][player.room_x].update(player); render_all(); curses.curs_set(2); gameplay_window.keypad(False); curses.nonl();
def main(sc): curses.nl() gameplay_window = curses.newwin(10, 30, 0, 0) map_window = curses.newwin(5, 10, 0, 35) stats_window = curses.newwin(5, 10, 5, 35) gameplay_window.keypad(True) curses.curs_set(0) curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_RED) player = player_.player((13, 4), (0, 0)) map = map_.map(5, 6) running = True def render_all(): stats_window.clear() gameplay_window.clear() player.render(gameplay_window, stats_window) map.rooms[player.room_y][player.room_x].render(gameplay_window, player) map.render(map_window, player) sc.refresh() gameplay_window.refresh() map_window.refresh() stats_window.refresh() render_all() while running: key = gameplay_window.getkey() if key == ' ': gameplay_window.addstr(2, 8, "Do you really") gameplay_window.addstr(3, 5, "want to quit (y/n) ?") gameplay_window.refresh() k = gameplay_window.getkey() if k == 'y': running = False render_all() continue player.update(key) player = map.rooms[player.room_y][player.room_x].update( player, gameplay_window) render_all() curses.curs_set(2) gameplay_window.keypad(False) curses.nonl()
def _close(self): """Close the curses interface.""" try: curses.noraw() curses.nl() curses.nocbreak() if self.screen: self.screen.keypad(False) curses.echo() curses.endwin() # restore original terminal size, colours and cursor console.reset() except Exception as e: logging.error('Exception on closing curses interface: %s', e)
def main(win): global stdscr stdscr = win curses.nl() curses.noecho() stdscr.timeout(0) stdscr.nodelay(1) while True: collect_unique_ip() update_screen() stdscr.refresh() stdscr.getch()
def close(): """ Close the text interface. """ if wait_on_close: sys.stdout.write(ansi.esc_set_title % (caption + ' - press a key to close window')) # redraw in case terminal didn't recognise ansi sequence redraw() while window.getch() == -1: pass if curses: curses.noraw() curses.nl() curses.nocbreak() screen.keypad(False) curses.echo() curses.endwin()
def init(a): global main_window, msgs, tabs global curs_state, escdelay global app app = a # Initialize curses and all top-level windows. escdelay = (False, '') curs_state = 2 if "ESCDELAY" in os.environ: escdelay = (True, os.environ["ESCDELAY"]) os.environ["ESCDELAY"] = "25" main_window = curses.initscr() main_window.touchwin() # Should be called before first refresh of any sub-window (curses manual) curses.noecho() curses.cbreak() curses.nl() curs_state = curses.curs_set(0)
def run(self): logging.debug('starting IntractiveMode') self.window = curses.initscr() self.window.nodelay(1) self.set_window_size() curses.nl() curses.noecho() curses.cbreak() try: self.mainloop() except (KeyboardInterrupt, SystemExit): self.cleanup() except Exception, err: logging.exception(err) self.cleanup() print err
def run(self): logging.debug("starting IntractiveMode") self.window = curses.initscr() self.window.nodelay(1) self.set_window_size() curses.nl() curses.noecho() curses.cbreak() try: self.mainloop() except (KeyboardInterrupt, SystemExit): self.cleanup() except Exception, err: logging.exception(err) self.cleanup() print err
def close(): """ Close the text interface. """ if wait_on_close: sys.stdout.write(ansi.esc_set_title % (caption + ' - press a key to close window')) sys.stdout.flush() # redraw in case terminal didn't recognise ansi sequence redraw() while window.getch() == -1: pass if curses: curses.noraw() curses.nl() curses.nocbreak() screen.keypad(False) curses.echo() curses.endwin()
def _handle_keypress(self, pressed_key): if pressed_key == 8 or pressed_key == 127 or pressed_key == curses.KEY_BACKSPACE: self.input_string = self.input_string[:-1] elif pressed_key == curses.KEY_ENTER or pressed_key == 10 or pressed_key == 13: final_output = self.matches[self.selected_option_index][1] curses.nocbreak() self.screen.keypad(False) curses.echo() curses.nl() curses.endwin() sys.stdout.flush() sys.stdout.buffer.write(final_output.encode('utf-8')) sys.stdout.buffer.write(b"\n") sys.stdout.flush() sys.exit() elif pressed_key == curses.KEY_DOWN: screen_vertical_real_estate = self._get_vertical_real_estate() if self.start + self.selected_option_index + 1 >= len( self.matches): # already at the bottom return if self.selected_option_index < screen_vertical_real_estate - 1: # visible page remains same but highlight the next self.selected_option_index += 1 else: # move the visible page down by 1 to highlight the next self.start += 1 elif pressed_key == curses.KEY_UP: if self.selected_option_index > 0: self.selected_option_index -= 1 else: self.start -= min(self.start, 1) # todo later: scroll wrap elif pressed_key == 27: # Exit on escape raise elif curses.ascii.isprint( pressed_key): # this also needs to be replaced by something. x, y = curses.getsyx() self.input_string = self.input_string + str(chr(pressed_key)) self.selected_option_index = 0
def __exit__(self, exc_type, exc_value, traceback): """Exit and action or call next kunai action """ curses.nl() curses.endwin() if self.action_name: # next action self.parser.pick_command(self.action_name) for const in self.parser.code_obj.co_consts: # XXX get only action method code object if isinstance(const, types.CodeType): self.parser.set_importmodule_code(const) exec(self.parser.code_obj, { # set globals self.render_name: self.args_for_action, }) else: # finish self.execute_command()
def setup(self): curses.curs_set(0) curses.noecho() curses.cbreak() curses.nl() self.screen.nodelay(1) self.screen.keypad(True) if curses.has_colors(): curses.start_color() for index, color in COLORS: curses.init_pair(index, color, curses.COLOR_BLACK) self.output_h = curses.LINES - 1 self.output_p = curses.newpad(self.output_h, curses.COLS) self.output_p.scrollok(True) self.output_p.idlok(1) self.refresh()
def __init__(self, encoding='UTF-8'): self.CODE = encoding self.buffer = [] curses.setupterm() self.win = curses.initscr() self.win.idlok(1) self.win.scrollok(True) curses.nl() curses.echo() curses.newwin(0, 0) self._start_point = (0, 0) y, x = self.win.getmaxyx() self.maxY, self.maxX = y - 1, x - 1 del y, x self.yMaxPoint, self.xMaxPoint = 0, 0 self.changePage = 10 self._new_line = [''] * (self.maxX + 1) self.table = [self._new_line[:] for i in range(self.maxY + 1)] self._actualY, self._actualX = (0, 0)
def __leaf_01(ql: Qiling): curses.nonl() # set non-blocking ql.os.stdscr.timeout(0) key = parse_key(ql.os.stdscr.getch()) if key == -1: ql.os.set_zf() ql.arch.regs.ax = 0 else: ql.log.debug(f"Has key: {hex(key)} ({curses.ascii.unctrl(key)})") ql.arch.regs.al = key ql.arch.regs.ah = get_scan_code(key) ql.os.clear_zf() # Buffer shouldn't be removed in this interrupt. curses.ungetch(key) ql.os.stdscr.timeout(-1) curses.nl()
async def __aexit__(self, type, value, tb): self.running = False # go to last line of screen, maybe cause scrolling? self.color_assigner.close() self.stdscr.keypad(0) curses.noraw() curses.nl() curses.echo() curses.endwin() try: signal.signal(signal.SIGINT, self.orig_sigint) except TypeError: self.log.exception('%s', f'orig_sigint: {self.orig_sigint!r}') try: signal.signal(signal.SIGTSTP, self.orig_sigtstp) except TypeError: self.log.exception('%s', f'orig_sigtstp: {self.orig_sigtstp!r}') try: signal.signal(signal.SIGWINCH, self.orig_sigwinch) except TypeError: self.log.exception('%s', f'orig_sigwinch: {self.orig_sigwinch!r}')
def init_curses(self): screen = curses.initscr() # don't echo key strokes on the screen curses.noecho() # read keystrokes instantly, without waiting for enter to ne pressed curses.cbreak() # enable keypad mode screen.keypad(1) curses.nl() screen.clear() screen.refresh() text_win = curses.newwin(22, 79, 0, 0) (input_pad, input_win) = make_text_box(screen, 1, 79, 23, 0) # Now store the windows self.screen = screen self.text_win = text_win self.input_pad = input_pad self.input_win = input_win screen.clear() screen.refresh()
def start_curses(stdscr, device): # Allow capture of KEY_ENTER via '\n'. curses.nl() # Draw the header, partitions table, and options menu menu = Menu(stdscr, device) menu.draw_menu() # The main loop that captures user input. while True: key = stdscr.getch() if key == -1: # no input continue if key == curses.KEY_RESIZE or key == 12: #^L menu.resize_menu() if key == curses.KEY_DOWN or key == curses.KEY_UP: menu.up_down(key) if key == curses.KEY_RIGHT or key == curses.KEY_LEFT: menu.left_right(key) if key == ord("\n"): menu.call("Selected") if key == ord("b") or key == ord("B"): menu.call("Bootable") if key == ord("d") or key == ord("D"): menu.call("Delete") if key == ord("h") or key == ord("H") or key == ord("?"): menu.call("Help") if key == ord("n") or key == ord("N"): menu.call("New") if key == ord("p") or key == ord("P"): menu.call("Print") if key == ord("q") or key == ord("Q"): menu.call("Quit") if key == ord("u") or key == ord("U"): menu.call("Units") if key == ord("t") or key == ord("T"): menu.call("New Table") if key == ord("W"): menu.call("Write")
def run(self): # try: curses.nl() # print 'waiting for key' # stdscr.addstr("waiting for key\n") # stdscr.refresh() global key stdscr.nodelay(1) while True: # stdscr.addstr("waiting for key\n\n") # stdscr.refresh() # k = raw_input() try: k = stdscr.getch() # stdscr.addstr("key retrieved\n\n") # if k == 'Escape': # print 'Escape' # elif k == 's': # print 's' # elif k == ord('e'): if k == ord('e'): stdscr.addstr("e pressed\n") # stdscr.addstr('k == {}\n', str(unichr(k))) # stdscr.addstr("k == \n") stdscr.refresh() key = 'e' stdscr.addch(key) stdscr.refresh() cleanup() break elif k == ord('r'): stdscr.addstr("r pressed\n") stdscr.refresh() elif k == ord('s'): stdscr.addstr("s pressed\n") stdscr.refresh() except curses.ERR: pass
def screen_setup(self): curses.start_color() curses.noecho() curses.cbreak() curses.nl() self.prompt = curses.newpad(1, 1024) self.prompt.move(0, 0) self.prompt.keypad(1) self.prompt.nodelay(1) self.main_window = curses.newwin(self.height - 2, self.width - 1, 0, 0) self.main_window.leaveok(1) self.main_window.scrollok(1) self.main_window.idlok(1) for fg in xrange(8): for bg in xrange(8): if fg or bg: curses.init_pair(fg * 8 + bg, fg, bg) self.status = curses.newpad(1, self.width) self.status.bkgd("_", curses.color_pair(36)) self.status.noutrefresh(0, 0, self.height - 2, 0, self.height - 1, self.width - 1)
def main(win): global stdscr stdscr = win if curses.has_colors(): bg = curses.COLOR_BLACK curses.init_pair(1, curses.COLOR_BLUE, bg) curses.init_pair(2, curses.COLOR_CYAN, bg) curses.nl() curses.noecho() stdscr.timeout(0) col = curses.COLS - 4 row = curses.LINES - 4 xpos = [0] * col ypos = [0] * row print col, row while True: x = randrange(0, col) + 2 y = randrange(0, row) + 2 stdscr.addch(y, x, ord('k')) curses.napms(50)
def main(win): global stdscr stdscr = win Res = True # It's used to store the directions directions = [] if curses.has_colors(): bg = curses.COLOR_BLACK curses.init_pair(1, curses.COLOR_BLUE, bg) curses.init_pair(2, curses.COLOR_CYAN, bg) curses.nl() curses.noecho() stdscr.timeout(0) mymap = CBobsMap() myBob = CgaBob() #myBob.FindPath(mymap) myBob.Epoch(mymap) while Res: ch = stdscr.getch() if ch == ord('q') or ch == ord('Q'): return #stdscr.erase() mymap.draw_map(stdscr) mymap.draw_track(stdscr) curses.napms(100) stdscr.refresh() Res = False time.sleep(100)
def _setup(self): """ Preforms needed setup returns a new curses window instance """ # reset x and y pos self.resetXY() # create the screen screen = curses.initscr() # Use the color of the existing terminal curses.start_color() curses.use_default_colors() curses.noecho() # disable newline mode curses.nl(False) # enables raw mode so we can handle all key codes ourselves curses.raw(True) # get the height and with of the screen to # avoid curses errors on write self.height, self.width = screen.getmaxyx() # setup scrolling screen.scrollok(True) # screen.setscrreg(0, self.height-1) # screen.idlok(1) # Clear screen screen.clear() return screen
w_status.addstr(4, 50, dronedict.get_pretty(config, dronedict.S_MAX_TILT) + ' ') w_status.addstr(5, 11, dronedict.get_pretty(config, dronedict.S_MAX_VERT) + ' ') w_status.addstr(5, 49, dronedict.get_pretty(config, dronedict.S_MAX_ROT) + ' ') mutex.release() w_status.refresh() event = screen.getch() if event == ord('q'): break move_drone(event) if event in right_events: hl_dir(w_rightjoy, event) elif event in left_events: hl_dir(w_leftjoy, event) elif event == ord('o'): drone.cutout(not config['cutout']) elif event == ord('i'): drone.wheels(not config['wheels']) curses.napms(70) if __name__ == '__main__': global drone, state, message, config, speed, battery state = S_DISCONNECTED message = speed = battery = '' config = dict() drone = minidrone.MiniDrone(mac=DRONEMAC, callback=refresh_data) curses.wrapper(main_loop) drone.die() curses.curs_set(1) curses.nl()
def __exit__(self, exc_type, exc_value, traceback): # Back to newline mode (TODO: is it needed?). curses.nl() curses.endwin() self.execute_action()
def main(screen): """Initialise and then run the main game loop.""" speed_up = 1 screen_y, screen_x = screen.getmaxyx() if screen_y < Game.SCREEN_MINHEIGHT or screen_x < Game.SCREEN_MINWIDTH: # Not big enough, throw a suitable exception errorstring = "Incorrect terminal size," \ "minimum size is %d x %d, actual size is %d x %d" % \ (Game.SCREEN_MINWIDTH, Game.SCREEN_MINHEIGHT, screen_x, screen_y) raise ValueError, errorstring global gameset,levelcount,game,success,lastdraw global chars_colors,objectlist curses.init_pair(1, curses.COLOR_RED, curses.COLOR_BLACK) curses.init_pair(2, curses.COLOR_CYAN, curses.COLOR_BLACK) curses.init_pair(3, curses.COLOR_YELLOW, curses.COLOR_BLACK) curses.curs_set(0) # turns off the visible cursor i=0 char=True while(True): screen.addstr(screen_y/2-2,screen_x/2-9,"ROBOT BOMB DEFUSER",curses.A_BOLD+curses.color_pair(i%5)); screen.addstr(screen_y/2+2,screen_x/2-14,"DEVELOPED BY DEEPAK KATHAYAT",curses.A_BOLD+curses.color_pair(i%5)); i=i+1 screen.addstr(screen_y/2+12,screen_x/2+20,"press spacebar to continue",curses.A_BLINK+curses.A_BOLD+curses.color_pair(0)); screen.nodelay(1) curses.beep() curses.flash() sleep(0.05) char = screen.getch() if char == ord(' '): break; screen.clear() while(True): screen.addstr(screen_y/2-2,screen_x/2-25,"THERE ARE FOUR LEVELS.",curses.A_BOLD+curses.color_pair(1)); screen.addstr(screen_y/2+2,screen_x/2-25,"LEVELS ARE NAMED IN THE ORDER IN WHICH EACH digit OCCURS IN THE INFAMOUS NUMBER PI",curses.A_BOLD+curses.color_pair(1)); screen.addstr(screen_y/2+3,screen_x/2-25,"AT ANY STAGE,YOU CAN SKIP LEVELS.JUST PRESS 'l'.",curses.A_BOLD+curses.color_pair(1)); screen.addstr(screen_y/2+7,screen_x/2-25,"ARROW KEYS are used for movement.",curses.A_BOLD+curses.color_pair(1)); screen.addstr(screen_y/2+8,screen_x/2-25,"P/p for pause.Q/q for quit.",curses.A_BOLD+curses.color_pair(1)); screen.addstr(screen_y/2+9,screen_x/2-25,"z for shooting bullets.USE THEM.",curses.A_BOLD+curses.color_pair(1)); screen.addstr(screen_y/2+10,screen_x/2-25,"HEALTH and TIME are IMPORTANT.DO NOT FORGET.",curses.A_BOLD+curses.color_pair(1)); screen.addstr(screen_y/2+12,screen_x/2+20,"press spacebar to continue",curses.A_BLINK+curses.A_BOLD+curses.color_pair(0)); screen.nodelay(1) curses.beep() curses.flash() sleep(0.05) char = screen.getch() if char == ord(' '): break screen.clear() while(True): screen.addstr(screen_y/2-5,screen_x/2-10,"CHOOSE THE PLAY MODE",curses.color_pair(i%5)+curses.A_BOLD) screen.addstr(screen_y/2-3,screen_x/2-9,"* AMATEUR : press 'a'",curses.A_BOLD); screen.addstr(screen_y/2-2,screen_x/2-10,"* LEGENDARY : press 'l'",curses.A_BOLD); i=i+1 screen.nodelay(1) curses.beep() curses.flash() sleep(0.05) char = screen.getch() if char == ord('a') or char == ord('l'): break sleep(1) screen.timeout(0) screen.nodelay(1) curses.nl() curses.curs_set(0) # turns off the visible cursor gameset=[] levelcount=0 num_of_levels=4 for i in range(num_of_levels): gameset.insert(i,Game(screen)) set_level(char) gameset[levelcount]._makeCD() gameset[levelcount].draw() initial_time = time() # time seconds as a real number tick_count = 0 tick_interval = 50 # game runs in 50ms steps (20Hz) timed_game_end = False # time-limited game ended curses.beep() curses.flash() charBomb = 'B' screen.nodelay(1) oldchar = curses.KEY_RIGHT stopgame=False lastdraw=False # start the game loop here while (True and not timed_game_end): char = screen.getch() if char == ord('q') or char==ord('Q'): break # quit elif char == ord('l'): levelcount=levelcount+1 if levelcount<num_of_levels: tick_count = 0 curses.flash() curses.beep() gameset[levelcount]._makeCD() else: break elif char == 27 : gameset[levelcount].game_over(0) game=False stopgame=True elif char == ord('p') or char==ord('P'): #pause: do_pause(screen) curses.flushinp() oldchar = char elif game == True: if char != oldchar: if char == curses.KEY_RIGHT: gameset[levelcount].handle_key(char) elif char == curses.KEY_LEFT: gameset[levelcount].handle_key(char) elif char == curses.KEY_UP: gameset[levelcount].handle_key(char) elif char == curses.KEY_DOWN: gameset[levelcount].handle_key(char) elif char == ord('z'):gameset[levelcount].handle_key(char) else: gameset[levelcount].handle_key(None) else: gameset[levelcount].handle_key(None) curses.flushinp() oldchar = char if game==False: curses.flash() curses.beep() continue if (gameset[levelcount]._robot._y<=-1 or gameset[levelcount]._robot._y+3 >= gameset[levelcount].screen_height or gameset[levelcount]._robot._x-2 <=0 or gameset[levelcount]._robot._x+1>=gameset[levelcount].screen_width): game=False success=False lastdraw=True curses.flash() curses.beep() elif (gameset[levelcount].codes!=[] and gameset[levelcount]._robot._y-2 <=gameset[levelcount]._bomb.pos[0] <= gameset[levelcount]._robot._y+2 and gameset[levelcount]._robot._x-4 <= gameset[levelcount]._bomb.pos[1] <= gameset[levelcount]._robot._x+4): show_explosion() game=False success=False lastdraw=True curses.flash() curses.beep() elif (gameset[levelcount].codes==[] and gameset[levelcount]._robot._y-2 <=gameset[levelcount]._bomb.pos[0] <= gameset[levelcount]._robot._y+2 and gameset[levelcount]._robot._x-4 <= gameset[levelcount]._bomb.pos[1] <= gameset[levelcount]._robot._x+4): levelcount += 1 tick_count = 0 if levelcount>=num_of_levels: game=False success=True lastdraw=True else:gameset[levelcount]._makeCD() curses.flash() curses.beep() if game==True: for code in gameset[levelcount].codes: xy=code.pos if gameset[levelcount]._robot._x-3 <= xy[1] <= gameset[levelcount]._robot._x+3 and gameset[levelcount]._robot._y-1 <= xy[0] <= gameset[levelcount]._robot._y+2: gameset[levelcount]._score=gameset[levelcount]._score+1 gameset[levelcount].codes.pop(gameset[levelcount].codes.index(code)) level_specific_property() gameset[levelcount].tick(tick_count) tick_count += tick_interval secs_elapsed_total = time() - initial_time ms_elapsed_total = int(secs_elapsed_total * 1000) target_real_ms = tick_count / speed_up ms_to_wait = max(0, target_real_ms - ms_elapsed_total) curses.napms(ms_to_wait) if game == True: if tick_count > gameset[levelcount].timelimit: # 10 seconds for 1st level show_explosion() success=False game=False lastdraw=True curses.beep() curses.flash() if not stopgame: try:gameset[levelcount].draw() except:pass if lastdraw==True: stopgame=True if(stopgame==True): if success==True: try:gameset[levelcount].game_over(1) except:gameset[levelcount-1].game_over(1) elif success==False: gameset[levelcount].game_over(0) sleep(SPEED) quit()
def editor(options): output = options.output input = options.input or output if not os.path.exists(output): open(output,'w').write('') if input and not os.path.exists(input): open(input,'w').write('') diff = compute_diff(output,input) delay = options.delay nonblock = options.nonblock if delay>0 and nonblock: time.sleep(min(delay*5,2)) screen = curses.initscr() curses.noecho() curses.cbreak() screen.keypad(1) save = True try: d=Document(screen, output, options=options) d.render() d.step = 0 d.diff = diff while True: if nonblock: if d.step>=len(diff): char=ord('x') else: char = 32 else: char = screen.getch() if char==curses.KEY_UP: d.up() elif char==curses.KEY_DOWN: d.down() elif (char==curses.KEY_RIGHT or char==32) and d.step<len(diff): command, r, c, text = diff[d.step] if command=='insert_line': d.insert_line(r,text) elif command=='delete_line': d.delete_line(r) elif command=='insert_text': d.insert_text(r,c,text) elif command=='delete_text': d.delete_text(r,c,int(text)) d.step+=1 # d.delete(random.randint(0,20),random.randint(0,20),10) elif char==curses.KEY_LEFT or char==ord('b'): d.revert() d.step=max(0,d.step-1) elif char==ord('+'): d.delay*=2 elif char==ord('-'): d.delay/=2 elif char==ord('n'): d.delay=0 elif char==ord('x'): break elif char==ord('q'): save = False break elif char==ord('s'): if input!=output: d.save(output) if input!=output and save: shutil.copyfile(input,output) finally: if delay>0 and nonblock: time.sleep(max(delay*5,2)) screen.keypad(0) curses.nocbreak() curses.echo() curses.endwin() curses.nl()
def module_funcs(stdscr): "Test module-level functions" for func in [curses.baudrate, curses.beep, curses.can_change_color, curses.cbreak, curses.def_prog_mode, curses.doupdate, curses.filter, curses.flash, curses.flushinp, curses.has_colors, curses.has_ic, curses.has_il, curses.isendwin, curses.killchar, curses.longname, curses.nocbreak, curses.noecho, curses.nonl, curses.noqiflush, curses.noraw, curses.reset_prog_mode, curses.termattrs, curses.termname, curses.erasechar, curses.getsyx]: func() # Functions that actually need arguments if curses.tigetstr("cnorm"): curses.curs_set(1) curses.delay_output(1) curses.echo() ; curses.echo(1) f = tempfile.TemporaryFile() stdscr.putwin(f) f.seek(0) curses.getwin(f) f.close() curses.halfdelay(1) curses.intrflush(1) curses.meta(1) curses.napms(100) curses.newpad(50,50) win = curses.newwin(5,5) win = curses.newwin(5,5, 1,1) curses.nl() ; curses.nl(1) curses.putp('abc') curses.qiflush() curses.raw() ; curses.raw(1) curses.setsyx(5,5) curses.tigetflag('hc') curses.tigetnum('co') curses.tigetstr('cr') curses.tparm('cr') curses.typeahead(sys.__stdin__.fileno()) curses.unctrl('a') curses.ungetch('a') curses.use_env(1) # Functions only available on a few platforms if curses.has_colors(): curses.start_color() curses.init_pair(2, 1,1) curses.color_content(1) curses.color_pair(2) curses.pair_content(curses.COLOR_PAIRS - 1) curses.pair_number(0) if hasattr(curses, 'use_default_colors'): curses.use_default_colors() if hasattr(curses, 'keyname'): curses.keyname(13) if hasattr(curses, 'has_key'): curses.has_key(13) if hasattr(curses, 'getmouse'): (availmask, oldmask) = curses.mousemask(curses.BUTTON1_PRESSED) # availmask indicates that mouse stuff not available. if availmask != 0: curses.mouseinterval(10) # just verify these don't cause errors m = curses.getmouse() curses.ungetmouse(*m)
def _restore(): curses.noraw() curses.nl()
def main(win): # we know that the first argument from curses.wrapper() is stdscr. # Initialize it globally for convenience. global stdscr stdscr = win if curses.has_colors(): bg = curses.COLOR_BLACK curses.init_pair(1, curses.COLOR_BLUE, bg) curses.init_pair(2, curses.COLOR_CYAN, bg) curses.nl() curses.noecho() stdscr.timeout(0) c = curses.COLS - 4 r = curses.LINES - 4 xpos = [0] * c ypos = [0] * r for j in range(4, -1, -1): xpos[j] = randrange(0, c) + 2 ypos[j] = randrange(0, r) + 2 j = 0 while True: x = randrange(0, c) + 2 y = randrange(0, r) + 2 stdscr.addch(y, x, ord('.')) stdscr.addch(ypos[j], xpos[j], ord('o')) j = next_j(j) stdscr.addch(ypos[j], xpos[j], ord('O')) j = next_j(j) stdscr.addch( ypos[j] - 1, xpos[j], ord('-')) stdscr.addstr(ypos[j], xpos[j] - 1, "|.|") stdscr.addch( ypos[j] + 1, xpos[j], ord('-')) j = next_j(j) stdscr.addch( ypos[j] - 2, xpos[j], ord('-')) stdscr.addstr(ypos[j] - 1, xpos[j] - 1, "/ \\") stdscr.addstr(ypos[j], xpos[j] - 2, "| O |") stdscr.addstr(ypos[j] + 1, xpos[j] - 1, "\\ /") stdscr.addch( ypos[j] + 2, xpos[j], ord('-')) j = next_j(j) stdscr.addch( ypos[j] - 2, xpos[j], ord(' ')) stdscr.addstr(ypos[j] - 1, xpos[j] - 1, " ") stdscr.addstr(ypos[j], xpos[j] - 2, " ") stdscr.addstr(ypos[j] + 1, xpos[j] - 1, " ") stdscr.addch( ypos[j] + 2, xpos[j], ord(' ')) xpos[j] = x ypos[j] = y ch = stdscr.getch() if ch == ord('q') or ch == ord('Q'): return elif ch == ord('s'): stdscr.nodelay(0) elif ch == ord(' '): stdscr.nodelay(1) curses.napms(50)
def __init__( self, x, y, width, height ): self.StatusPosition = width - MAXSTATUSLENGTH NCursesUI.DecoratedWindow.__init__( self, None, x, y, width, height ) curses.nl()