我们从Python开源项目中,提取了以下40个代码示例,用于说明如何使用curses.KEY_RIGHT。
def build_keymap(args): """ Function build_keymap returns a dictionary from curses keys to game.Keys. """ if args.vimkeys: return { ord('k'): Keys.UP, ord('j'): Keys.DOWN, ord('h'): Keys.LEFT, ord('l'): Keys.RIGHT, ord(' '): Keys.PROBE, ord('f'): Keys.FLAG, } return { curses.KEY_UP: Keys.UP, curses.KEY_DOWN: Keys.DOWN, curses.KEY_LEFT: Keys.LEFT, curses.KEY_RIGHT: Keys.RIGHT, ord('\n'): Keys.PROBE, ord('f'): Keys.FLAG, }
def update(cls): key = cls.getch() if key is not None: if key == curses.KEY_UP: cls.PAD_Y = max(cls.PAD_Y - 1, 0) elif key == curses.KEY_DOWN: cls.PAD_Y = min( cls.PAD_Y + 1, cls.PAD_HEIGHT - (cls.HEIGHT + 1) ) elif key == curses.KEY_LEFT: cls.PAD_X = max(cls.PAD_X - 1, 0) elif key == curses.KEY_RIGHT: cls.PAD_X = min( cls.PAD_X + 1, cls.PAD_WIDTH - (cls.WIDTH + 1) ) elif key == ord('q'): cls.trigger('quit') for y in range(cls.PAD_Y, cls.PAD_Y + cls.HEIGHT): s = cls.MAP[y][cls.PAD_X:cls.PAD_X + cls.PAD_HEIGHT] s = ''.join(x for x in s) cls.addstr(s, cls.PAD_X, y) cls.refresh()
def focus(self): modeline.update_activeWindow("Map") curses.curs_set(0) while True: event = self.mapwin.getch() # if event == -1: # continue logging.info(event) try_handle_global_event(event) if event == curses.KEY_UP: self.pan("up") if event == curses.KEY_DOWN: self.pan("down") if event == curses.KEY_LEFT: self.pan("left") if event == curses.KEY_RIGHT: self.pan("right") if event == curses.KEY_NPAGE: self.zoom_out(5) if event == curses.KEY_PPAGE: self.zoom_in(5)
def update_screen(): """ Updates the screen each time a key is pressed. """ if not GUI.gui_stopped: if GUI.key == curses.KEY_DOWN: GUI.on_key_down() elif GUI.key == curses.KEY_UP: GUI.on_key_up() elif GUI.key == curses.KEY_LEFT: GUI.on_key_left() elif GUI.key == curses.KEY_RIGHT: GUI.on_key_right() if GUI.key == ord("\n") and GUI.row_num != 0: GUI.on_key_enter() GUI.box.erase() GUI.display_list() GUI.add_bottom_menus() GUI.screen.refresh() GUI.box.refresh()
def __init__(self, x, y, window): self.body_list = [] self.hit_score = 0 self.timeout = TIMEOUT for i in range(SNAKE_LENGTH, 0, -1): self.body_list.append(Body(x - i, y)) self.body_list.append(Body(x, y, '0')) self.window = window self.direction = KEY_RIGHT self.last_head_coor = (x, y) self.direction_map = { KEY_UP: self.move_up, KEY_DOWN: self.move_down, KEY_LEFT: self.move_left, KEY_RIGHT: self.move_right }
def __init__(self, x, y, window): self.body_list = [] self.hit_score = 0 self.timeout = TIMEOUT #0 Append The Snake's range to the Body object for Snakes Body for i in range(SNAKE_LENGTH, 0, -1): self.body_list.append(Body(x - i, y)) #1 Define and append the snakes head self.body_list.append(Body(x, y, '0')) #2 define the window self.window = window #3 Move snake to right when game starts self.direction = KEY_RIGHT #4 set snakes lst head coordinate self.last_head_coor = (x, y) #5 define direction map self.direction_map = { KEY_UP: self.move_up, KEY_DOWN: self.move_down, KEY_LEFT: self.move_left, KEY_RIGHT: self.move_right }
def put(self, char): pos = self._cursor.position cnt = len(self._text) if isinstance(char, str) and cnt < self._max_len and ord(char) >= 0x20: self._text = self._text[:pos] + char + self._text[pos:] self._cursor.count = len(self._text) self._cursor.position = pos + 1 elif char == curses.KEY_LEFT and pos > 0: self._cursor.position = pos - 1 elif char == curses.KEY_RIGHT and pos < cnt: self._cursor.position = pos + 1 elif char == curses.KEY_HOME: self._cursor.position = 0 elif char == curses.KEY_END: self._cursor.position = cnt elif char == curses.KEY_BACKSPACE and pos > 0: self._text = self._text[:pos - 1] + self._text[pos:] self._cursor.count = len(self._text) self._cursor.position = pos - 1 elif char == curses.KEY_DC: self._text = self._text[:pos] + self._text[pos + 1:] self._cursor.count = len(self._text)
def handle_key(self, k): if k == ord('q'): self.close(None) elif k == ord('d'): self._change_date() elif k == ord('l'): self._change_level() elif k == ord('f'): self._change_facility() elif k == ord('h'): self._change_host() elif k == ord('p'): self._change_program() elif k == curses.KEY_NPAGE: self._buf.go_to_next_page() elif k == curses.KEY_PPAGE: self._buf.go_to_previous_page() elif k == curses.KEY_DOWN: self._buf.go_to_next_line() elif k == curses.KEY_UP: self._buf.go_to_previous_line() elif k == curses.KEY_RIGHT: self.scroll_right() elif k == curses.KEY_LEFT: self.scroll_left()
def _alternative_left_right(term): r""" Determine and return mapping of left and right arrow keys sequences. :arg blessed.Terminal term: :class:`~.Terminal` instance. :rtype: dict This function supports :func:`get_terminal_sequences` to discover the preferred input sequence for the left and right application keys. Return dict of sequences ``term._cuf1``, and ``term._cub1``, valued as ``KEY_RIGHT``, ``KEY_LEFT`` (when appropriate). It is necessary to check the value of these sequences to ensure we do not use ``u' '`` and ``u'\b'`` for ``KEY_RIGHT`` and ``KEY_LEFT``, preferring their true application key sequence, instead. """ keymap = dict() if term._cuf1 and term._cuf1 != u' ': keymap[term._cuf1] = curses.KEY_RIGHT if term._cub1 and term._cub1 != u'\b': keymap[term._cub1] = curses.KEY_LEFT return keymap
def main(win,args): SCSP = ScreenSpace(win) SNK = Snake(win,args) try: while True: SNK.render(SCSP,args) SCSP.render(clear=False,ref=False) gc = SCSP.win.getch() if gc in [ord("a"),curses.KEY_LEFT]: SNK.dir = SNK.turnleft() if gc in [ord("d"),curses.KEY_RIGHT]: SNK.dir = SNK.turnright() if gc == ord("q"): SCSP.destroy() sys.exit() SCSP.win.erase() time.sleep(args.delay) except KeyboardInterrupt: pass
def runDay(scr, rollover, topString, bottomString, start=None): if(rollover): if(start is None): day = date.today() else: day = date(start.year, start.month, start.day) else: if(start is None): day = datetime.date.today() else: day = datetime.date(start.year, start.month, start.day) c = curses.KEY_MAX cursor = 3 while(c != 10): displayDay(scr, day, cursor, topString, bottomString) c = scr.getch() if(c == curses.KEY_RIGHT) and cursor < len(str(day))-1: cursor += 1 if(cursor == 4 or cursor == 7): cursor += 1 elif(c == curses.KEY_LEFT) and cursor > 0: cursor -= 1 if(cursor == 4 or cursor == 7): cursor -= 1 elif(c == curses.KEY_UP): day = alterDigitDay(cursor, day, 1) elif(c == curses.KEY_DOWN): day = alterDigitDay(cursor, day, -1) else: try: i = int(c) - 48 if(i >= 0 and i < 10): day = updateDigitDay(cursor, day, i) except ValueError: pass return datetime.date(day.year, day.month, day.day)
def runTime(scr, rollover, topString, bottomString, start=None): if(rollover): if(start is None): t = time() else: t = time(start.hour, start.minute, start.second) else: if(start is None): t = datetime.time() else: t = datetime.time(start.hour, start.minute, start.second) c = curses.KEY_MAX cursor = 3 while(c != 10): displayTime(scr, t, cursor, topString, bottomString) c = scr.getch() if(c == curses.KEY_RIGHT) and cursor < len(str(t))-1: cursor += 1 if(cursor == 2 or cursor == 5): cursor += 1 elif(c == curses.KEY_LEFT) and cursor > 0: cursor -= 1 if(cursor == 2 or cursor == 5): cursor -= 1 elif(c == curses.KEY_UP): t = alterDigitTime(cursor, t, 1) elif(c == curses.KEY_DOWN): t = alterDigitTime(cursor, t, -1) else: try: i = int(c) - 48 if(i >= 0 and i < 10): t = updateDigitTime(cursor, t, i) except ValueError: pass return datetime.time(t.hour, t.minute, t.second)
def processkey(self, key, win): h, w = win.getmaxyx() if (key == ord(' ')): weapon = self.arsenal[self.active_weapon] if (weapon[1] != 0): self.shoot() if(weapon[1] != -1): weapon[1] = max(0, weapon[1] - 1) return True else: self.weapon_display_timer = 50 elif (key == curses.KEY_LEFT): if self.angle <= pi/2: self.angle = pi - self.angle else: self.move(-1) elif (key == curses.KEY_RIGHT): if self.angle >= pi/2: self.angle = pi - self.angle else: self.move(1) elif (key == curses.KEY_UP): if (self.angle <= pi/2): self.angle = min(pi/2.001, self.angle+0.01) else: self.angle = max(pi/1.999, self.angle-0.01) elif (key == curses.KEY_DOWN): if (self.angle <= pi/2): self.angle = max(0, self.angle-0.01+pi/8)-pi/8 else: self.angle = min(pi*9/8, self.angle+0.01) elif (key == ord('+')): self.power = min(1.00, self.power+0.01) elif (key == ord('-')): self.power = max(0.00, self.power-0.01) elif (key in map(lambda k : ord(str(k)), range(10))): n = int(chr(key)) self.active_weapon = (n-1) % len(self.arsenal) self.weapon_display_timer = 50 return False
def run_main_loop(self): self.draw_ui() while 1: c = self.window.getch() if curses.keyname(c) in [b'h', b'H']: self.show_help() elif curses.keyname(c) in [b'p', b'P']: self.play() elif curses.keyname(c) in [b'q', b'Q']: return None elif c == 27: self.returnString = self.dir.get_current_path() return self.returnString elif c == curses.KEY_ENTER or c == 10: self.returnString = self.dir.get_current_path() return self.returnString elif c == curses.KEY_UP: if self.selected_index > 0: self.selected_index -= 1 self.draw_ui() elif c == curses.KEY_DOWN: if self.selected_index < self.dir.max_entries_on_level()-1: self.selected_index += 1 self.draw_ui() elif c == curses.KEY_LEFT: self.leave_dir() self.draw_ui() elif c == curses.KEY_RIGHT: self.enter_dir() self.draw_ui() elif c == curses.KEY_RESIZE: self.draw_ui()
def on_key(self, ch): if ch == curses.KEY_LEFT: if self.selected > 0: self.selected -= 1 elif ch == curses.KEY_RIGHT: if self.selected + 1 < len(self.items): self.selected += 1 else: return False self.value = self.items[self.selected] self.update() return True
def on_key(self, ch): x = self.pos # ascii 32-126 (inclusive) if curses.ascii.isprint(ch): if len(self.value) < self.max_length: self.value = self.value[:x] + chr(ch) + self.value[x:] self.pos += 1 elif ch == curses.KEY_LEFT: if x > 0: self.pos -= 1 elif ch == curses.KEY_RIGHT: if x < len(self.value): self.pos += 1 elif ch == curses.KEY_BACKSPACE: if x > 0: self.value = self.value[:x - 1] + self.value[x:] self.pos -= 1 elif ch == curses.KEY_DC: if x < len(self.value): self.value = self.value[:x] + self.value[x + 1:] elif ch == curses.KEY_HOME: self.pos = 0 elif ch == curses.KEY_END: self.pos = len(self.value) else: return False self.update() return True
def on_key(self, ch): if not self.active: return if self.selected: if ch in (curses.ascii.ESC, curses.KEY_BACKSPACE): self.cancel_selection() elif ch == curses.KEY_LEFT: if self.selection > 0 and self.selection < 4 or self.selection > 4: self.set_selection(self.selection - 1) elif ch == curses.KEY_RIGHT: if self.selection < 3 or self.selection > 3 and self.selection < 7: self.set_selection(self.selection + 1) elif ch == curses.KEY_UP: if self.selection > 3: self.set_selection(self.selection - 4) elif ch == curses.KEY_DOWN: if self.selection < 4 and self.selected_source == 'hand': self.set_selection(self.selection + 4) elif ch in (curses.KEY_ENTER, curses.ascii.SP): self.confirm_selection() else: if ch == curses.KEY_LEFT: if self.selection > 0: self.set_selection(self.selection - 1) elif ch == curses.KEY_RIGHT: if self.selection + 1 < len(self.selectable_sources): self.set_selection(self.selection + 1) elif ch in (curses.KEY_ENTER, curses.ascii.SP): self.confirm_selection()
def poll_event(self): """ Checks if an event happens and returns a string related to the event. Returns -1 if nothing happened during self.screen.timeout milliseconds. If the event is a normal (letter) key press, the letter is returned (case sensitive) :return: Event type """ self.mutex.acquire() ch = self.screen.getch() self.mutex.release() if ch == -1: return EVENT_SKIP elif ch == 27: return EVENT_ESC elif ch == curses.KEY_RESIZE: return EVENT_RESIZE elif ch == 10 or ch == curses.KEY_ENTER: return EVENT_ENTER elif ch == 127 or ch == curses.KEY_BACKSPACE: return EVENT_BACKSPACE elif ch == curses.KEY_UP: return EVENT_UP elif ch == curses.KEY_DOWN: return EVENT_DOWN elif ch == curses.KEY_LEFT: return EVENT_LEFT elif ch == curses.KEY_RIGHT: return EVENT_RIGHT elif ch == 3: return EVENT_CTRL_C elif ch == 409: return EVENT_CLICK elif 0 <= ch < 256: return chr(ch) else: return EVENT_UNHANDLED
def test_should_move_cursor_right(self): input = TextInput(max_len=10) input.put('a') input.put(curses.KEY_LEFT) input.put(curses.KEY_RIGHT) self.assertEqual(1, input.cursor)
def test_should_not_move_cursor_after_right_boundary(self): input = TextInput(max_len=10) input.put('a') input.put(curses.KEY_RIGHT) self.assertEqual(1, input.cursor)
def test_should_handle_key_right(self): self._parent_window.getmaxyx.return_value = (9, 30) win = Datetime(self._manager, 'Date', datetime.datetime.utcnow()) win.handle_key(curses.KEY_RIGHT) win.refresh() self._child_window.chgat.assert_called_once_with(2, 7, 2, 0)
def test_should_handle_key_left(self): self._parent_window.getmaxyx.return_value = (9, 30) win = Datetime(self._manager, 'Date', datetime.datetime.utcnow()) win.handle_key(curses.KEY_RIGHT) win.handle_key(curses.KEY_LEFT) win.refresh() self._child_window.chgat.assert_called_once_with(2, 2, 4, 0)
def command(self, char): """handle page specific commands""" if char == curses.KEY_DOWN or char == ord('j'): if self.pad_pos < self.row_count-1: self.pad_pos += 1 elif char == curses.KEY_UP or char == ord('k'): if self.pad_pos > 0: self.pad_pos -= 1 elif char == curses.KEY_NPAGE or char == ord('J'): if self.pad_pos < self.row_count-((self.max_y)/2): self.pad_pos += (self.max_y)/2 else: self.pad_pos = self.row_count-1 elif char == curses.KEY_PPAGE or char == ord('K'): if self.pad_pos > ((self.max_y)/2): self.pad_pos -= (self.max_y)/2 else: self.pad_pos = 0 elif char == curses.KEY_RIGHT or char == ord('l'): if self.row_index[self.pad_pos][0] == 'vessel': vessel = self.row_index[self.pad_pos][1] return ('VESSEL_DETAIL', vessel) if self.row_index[self.pad_pos][0] == 'target': vessel = self.row_index[self.pad_pos][1] path = self.row_index[self.pad_pos][2] return ('TARGET_DETAIL', (vessel, path)) return (None, None)
def _create_pocket(self): pocket_name = "" while True: self.screen.clear() self._draw_tab_bar() self.screen.addstr(2, 2, "Pocket name:") self.screen.addstr(4, 4, pocket_name) c = self.screen.getch() if c == 27: self._status = "Cancelled" break elif c == curses.KEY_ENTER or c == 10 or c == 13: ec = await api.Pocket.create(self._ws, pocket_name) if ec: self._status = ec.name else: self._status = "Created" break elif c == curses.KEY_BACKSPACE: pocket_name = pocket_name[:-1] elif c == curses.KEY_LEFT or c == curses.KEY_RIGHT: pass else: pocket_name += chr(c)
def _enter_password_tab2(self): password = "" while True: self.screen.clear() self._draw_tab_bar() self.screen.addstr(2, 2, "Password:") self.screen.addstr(4, 2, "*" * len(password)) c = self.screen.getch() if c == curses.KEY_BACKSPACE: password = password[:-1] elif c == curses.KEY_ENTER or c == 10 or c == 13: return password elif c == curses.KEY_LEFT: self._current_tab -= 1 if self._current_tab < 0: self._current_tab = len(self._account_names) - 1 await self._activate_account() return None elif c == curses.KEY_RIGHT: self._current_tab += 1 if self._current_tab >= len(self._account_names): self._current_tab = 0 await self._activate_account() return None else: password += chr(c)
def display(self): self.window.clear() self.showdetail() while True: self.has_focus = True self.next_window.has_focus = False self.window.refresh() curses.doupdate() self.update() key = self.window.getch() if key in [curses.KEY_ENTER, ord('\n')]: return self.position if key == curses.KEY_UP: if self.position == 0: self.navigate(self.last_item_index) else: self.navigate(-1) elif key == curses.KEY_DOWN: self.navigate(1) elif key == curses.KEY_RIGHT or key == curses.KEY_LEFT: self.has_focus = False self.update() self.next_window.display()
def display(self): self.window.clear() self.showdetail() while True: self.has_focus = True self.next_window.has_focus = False self.window.refresh() curses.doupdate() self.update() key = self.window.getch() if key in [curses.KEY_ENTER, ord('\n')]: self.action() return if key == curses.KEY_UP: if self.position == 0: self.navigate(self.last_item_index) else: self.navigate(-1) elif key == curses.KEY_DOWN: self.navigate(1) elif key == curses.KEY_RIGHT or key == curses.KEY_LEFT: self.has_focus = False self.update() return # TODO: scrolling this
def main(): environ["TERM"] = 'Eterm' initscr() curs_set(0) try: win = newwin(16, 60, 0, 0) win.keypad(True) win.nodelay(True) win.border('|', '|', '-', '-', '+', '+', '+', '+') win.addch(4, 44, '@') win.addstr(0, 5, ' Eat all the OPNFV bugs by FunTest! ') win.addstr(15, 7, ' Left,Right,Up,Down: move; other keys: quit ') snake = [[20, 7], [19, 7], [18, 7], [17, 7], [16, 7], [15, 7], [14, 7], [13, 7]] key = KEY_RIGHT body = '~FUNTEST' ind = 0 while key != 27: win.addstr(0, 44, ' Score: ' + str(len(snake) - len(body)) + ' ') win.timeout(140 - 2 * len(snake)) getkey = win.getch() key = key if getkey == -1 else getkey snake.insert( 0, [snake[0][0] + (key == KEY_RIGHT and 1 or key == KEY_LEFT and -1), snake[0][1] + (key == KEY_DOWN and 1 or key == KEY_UP and -1)]) win.addch(snake[len(snake) - 1][1], snake[len(snake) - 1][0], ' ') if win.inch(snake[0][1], snake[0][0]) & 255 == 32: snake.pop() elif win.inch(snake[0][1], snake[0][0]) & 255 == ord('@'): c = [n for n in [[randrange(1, 58, 1), randrange(1, 14, 1)] for x in range(len(snake))] if n not in snake] win.addch(c == [] and 4 or c[0][1], c == [] and 44 or c[0][0], '@') else: break ind += 1 win.addch(snake[0][1], snake[0][0], body[ind % len(body)]) finally: endwin() print('\nSnake.PY-26ines by Kris Cieslak (defaultset.blogspot.com).') print('OPNFV adaptation by Functest dream team.') score = str(len(snake) - len(body) - 1) print ('Thanks for playing, your score: %s.' % score) print('Find and fix more bugs in your real OPNFV setup!\n')
def keys_init(self): """Define methods for each key. """ self.keys = { curses.KEY_BACKSPACE: self.backspace, CTRL('h'): self.backspace, curses.ascii.BS: self.backspace, curses.ascii.DEL: self.backspace, curses.ascii.ETX: self.close, curses.KEY_DC: self.del_char, CTRL('d'): self.del_char, CTRL('u'): self.del_to_bol, CTRL('k'): self.del_to_eol, curses.KEY_DOWN: self.down, CTRL('n'): self.down, curses.KEY_END: self.end, CTRL('e'): self.end, curses.KEY_F1: self.help, curses.KEY_HOME: self.home, CTRL('a'): self.home, curses.KEY_ENTER: self.insert_line_or_quit, curses.ascii.NL: self.insert_line_or_quit, curses.ascii.LF: self.insert_line_or_quit, "\n": self.insert_line_or_quit, curses.KEY_LEFT: self.left, CTRL('b'): self.left, curses.KEY_NPAGE: self.page_down, curses.KEY_PPAGE: self.page_up, CTRL('v'): self.paste, CTRL('x'): self.quit, curses.KEY_F2: self.quit, curses.KEY_F3: self.quit_nosave, curses.ascii.ESC: self.quit_nosave, curses.KEY_RESIZE: self.resize, -1: self.resize, curses.KEY_RIGHT: self.right, CTRL('f'): self.right, curses.KEY_UP: self.up, CTRL('p'): self.up, }
def keypress(self, char): # right arrow select a user/group to chat with if char == curses.KEY_RIGHT: self.refresh_body() self.update_chat() self.showing = self.selection current_id = self.slack_client.active[self.showing].id current_name = self.slack_client.active[self.showing].name for m in self.slack_client.last_messages(current_id): self.push_chat(m['user'], m['text']) return # moves to the user/group below current selection elif char == curses.KEY_DOWN: if self.selection < len(self.slack_client.active) - 1: self.set_body_selection(self.selection + 1) self.refresh_body() return # move cursor one position up elif char == curses.KEY_UP: if self.selection > 0: self.set_body_selection(self.selection - 1) self.refresh_body() return # send the content on the textbox elif char == curses.KEY_ENTER or chr(char) == "\n": # Fixme: send message as 'me', should be username self.push_chat('me', self.text) self.send_text() return # delete a character elif chr(char) == self.del_char or chr(char) == "\x7f": self.backspace() return # send the char to textbox area else: self.text += chr(char) self.refresh_textarea(char) return # This method is callable for testing porpuses only
def runDateTime(scr, rollover, topString, bottomString, start=None): if(rollover): if(start is None): d = date.today() t = time() else: d = date(start.year, start.month, start.day) t = time(start.hour, start.minute, start.second) else: if(start is None): d = datetime.date.today() t = datetime.time() else: d = datetime.date(start.year, start.month, start.day) t = datetime.time(start.hour, start.minute, start.second) c = curses.KEY_MAX cursor = 3 while(c != 10): displayDateTime(scr, d, t, cursor, topString, bottomString) c = scr.getch() if(c == curses.KEY_RIGHT) and cursor < 18: cursor += 1 if(cursor in (4, 7, 10, 13, 16)): cursor += 1 elif(c == curses.KEY_LEFT) and cursor > 0: cursor -= 1 if(cursor in (4, 7, 10, 13, 16)): cursor -= 1 elif(c == curses.KEY_UP): if(cursor < 10): d = alterDigitDay(cursor, d, 1) else: t = alterDigitTime(cursor - 11, t, 1) elif(c == curses.KEY_DOWN): if(cursor < 10): d = alterDigitDay(cursor, d, -1) else: t = alterDigitTime(cursor - 11, t, -1) else: try: i = int(c) - 48 if(i >= 0 and i < 10): if(cursor < 10): d = updateDigitDay(cursor, d, i) else: t = updateDigitTime(cursor - 11, t, i) except ValueError: pass return datetime.datetime(d.year, d.month, d.day, t.hour, t.minute, t.second)
def c_main(stdscr): cargo_cult_routine(stdscr) stdscr.nodelay(0) mydir = factory(start) mydir.expand() curidx = 3 pending_action = None pending_save = False while True: stdscr.clear() curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_BLUE) line = 0 offset = max(0, curidx - curses.LINES + 3) for data, depth in mydir.traverse(): if line == curidx: stdscr.attrset(curses.color_pair(1) | curses.A_BOLD) if pending_action: getattr(data, pending_action)() pending_action = None elif pending_save: global result result = data.name return else: stdscr.attrset(curses.color_pair(0)) if 0 <= line - offset < curses.LINES - 1: stdscr.addstr(line - offset, 0, data.render(depth, curses.COLS)) line += 1 stdscr.refresh() ch = stdscr.getch() if ch == curses.KEY_UP: curidx -= 1 elif ch == curses.KEY_DOWN: curidx += 1 elif ch == curses.KEY_PPAGE: curidx -= curses.LINES if curidx < 0: curidx = 0 elif ch == curses.KEY_NPAGE: curidx += curses.LINES if curidx >= line: curidx = line - 1 elif ch == curses.KEY_RIGHT: pending_action = 'expand' elif ch == curses.KEY_LEFT: pending_action = 'collapse' elif ch == ESC: return elif ch == ord('\n'): pending_save = True curidx %= line ################################################################################
def on_key(self, ch): if not self.active or self.disabled: return if not self.active.on_key(ch): y, x = self.position(self.active) if ch == curses.KEY_UP: if y > 0: self.set_active(self.rows[y - 1][self.defaults[y - 1]]) elif ch in (curses.KEY_DOWN, curses.KEY_ENTER): if y < len(self.rows) - 1: self.set_active(self.rows[y + 1][self.defaults[y + 1]]) elif ch == curses.KEY_LEFT: if x > 0: self.set_active(self.rows[y][x - 1]) elif ch == curses.KEY_RIGHT: if x < len(self.rows[y]) - 1: self.set_active(self.rows[y][x + 1]) elif ch == curses.ascii.TAB: # Right if x < len(self.rows[y]) - 1: self.set_active(self.rows[y][x + 1]) # Down, ignoring defaults elif y < len(self.rows) - 1: self.set_active(self.rows[y + 1][0]) else: self.set_active(self.rows[0][0]) elif ch == curses.KEY_BTAB: # Left if x > 0: self.set_active(self.rows[y][x - 1]) # Up elif y > 0: col = len(self.rows[y - 1]) - 1 self.set_active(self.rows[y - 1][col]) else: row = len(self.rows) - 1 col = len(self.rows[row]) - 1 self.set_active(self.rows[row][col])
def keyloop(stdscr): # Clear the screen and display the menu of keys stdscr.clear() stdscr_y, stdscr_x = stdscr.getmaxyx() menu_y = (stdscr_y-3)-1 display_menu(stdscr, menu_y) # Allocate a subwindow for the Life board and create the board object subwin = stdscr.subwin(stdscr_y-3, stdscr_x, 0, 0) board = LifeBoard(subwin, char=ord('*')) board.display(update_board=False) # xpos, ypos are the cursor's position xpos, ypos = board.X//2, board.Y//2 # Main loop: while (1): stdscr.move(1+ypos, 1+xpos) # Move the cursor c = stdscr.getch() # Get a keystroke if 0<c<256: c = chr(c) if c in ' \n': board.toggle(ypos, xpos) elif c in 'Cc': erase_menu(stdscr, menu_y) stdscr.addstr(menu_y, 6, ' Hit any key to stop continuously ' 'updating the screen.') stdscr.refresh() # Activate nodelay mode; getch() will return -1 # if no keystroke is available, instead of waiting. stdscr.nodelay(1) while (1): c = stdscr.getch() if c != -1: break stdscr.addstr(0,0, '/') stdscr.refresh() board.display() stdscr.addstr(0,0, '+') stdscr.refresh() stdscr.nodelay(0) # Disable nodelay mode display_menu(stdscr, menu_y) elif c in 'Ee': board.erase() elif c in 'Qq': break elif c in 'Rr': board.makeRandom() board.display(update_board=False) elif c in 'Ss': board.display() else: pass # Ignore incorrect keys elif c == curses.KEY_UP and ypos>0: ypos -= 1 elif c == curses.KEY_DOWN and ypos<board.Y-1: ypos += 1 elif c == curses.KEY_LEFT and xpos>0: xpos -= 1 elif c == curses.KEY_RIGHT and xpos<board.X-1: xpos += 1 else: # Ignore incorrect keys pass
def game_loop(stdscr, columns, rows, num_mines): game = minesweeper.Game.create_random(columns, rows, num_mines) Point = namedtuple('Point', ['x', 'y'], verbose=True) cursor_pos = Point(0, 0) while True: stdscr.clear() game_rect = draw_screen(stdscr, game) # restrict cursor to the game field cursor_pos = Point( clamp(cursor_pos.x, game_rect.x, game_rect.x+game_rect.width-1), clamp(cursor_pos.y, game_rect.y, game_rect.y+game_rect.height-1) ) stdscr.move(cursor_pos.y, cursor_pos.x) stdscr.refresh() c = stdscr.getch() if c == curses.KEY_LEFT: cursor_pos = Point(cursor_pos.x-2, cursor_pos.y) if c == curses.KEY_RIGHT: cursor_pos = Point(cursor_pos.x+2, cursor_pos.y) if c == curses.KEY_UP: cursor_pos = Point(cursor_pos.x, cursor_pos.y-1) if c == curses.KEY_DOWN: cursor_pos = Point(cursor_pos.x, cursor_pos.y+1) if c == curses.KEY_ENTER or c == 10: game.toggle_mark(*cursor_to_index(cursor_pos, game_rect)) if c == " " or c == 32: game.reveal(*cursor_to_index(cursor_pos, game_rect)) if c == 27: # Escape selected = open_menu(stdscr, ["Continue", "New Game", "Exit"]) if selected == "Exit": return elif selected == "New Game": columns, rows, num_mines = open_difficulty_menu(stdscr) return game_loop(stdscr, columns, rows, num_mines) if game.is_lost() or game.is_solved(): # reveal the complete solution game.reveal_all() stdscr.clear() draw_screen(stdscr, game) # wait for user to press any key curses.curs_set(False) c = stdscr.getch() curses.curs_set(True) break
def start(self): self._status = "" self._active_account = None self._active_pocket = None while True: self._active_account, self._account_names = \ await api.Account.list(self._ws) if self._active_account is not None: break await self._select_account() self._current_tab = self._account_names.index(self._active_account) self._current_pocket = 0 while True: await self.display_main_window() c = self.screen.getch() if c == curses.KEY_RIGHT and len(self._account_names) > 1: self._current_tab += 1 if self._current_tab >= len(self._account_names): self._current_tab = 0 await self._activate_account() elif c == curses.KEY_LEFT and len(self._account_names) > 1: self._current_tab -= 1 if self._current_tab < 0: self._current_tab = len(self._account_names) - 1 await self._activate_account() elif c == curses.KEY_DOWN: self._current_pocket += 1 if self._current_pocket > len(self._pockets) + 1: self._current_pocket = 0 elif c == curses.KEY_UP: self._current_pocket -= 1 if self._current_pocket < 0: self._current_pocket = len(self._pockets) + 1 elif c == curses.KEY_ENTER or c == 10 or c == 13: if self._current_pocket == len(self._pockets) + 1: await self._create_pocket() else: await self._send_screen()
def _send_screen(self): ec, self._history = await api.Wallet.history(self._ws, self._active_pocket) self._send_fields = ["", "", "", ""] self._selected_send_item = 0 while True: await self._display_history() c = self.screen.getch() if c == curses.KEY_UP: self._selected_send_item -= 1 if self._selected_send_item < 0: self._selected_send_item = 3 elif c == curses.KEY_DOWN: self._selected_send_item += 1 if self._selected_send_item > 3: self._selected_send_item = 0 elif c == curses.KEY_ENTER or c == 10 or c == 13: if self._selected_send_item == 0: break _, addr, amount, fee = self._send_fields try: decimal.Decimal(amount) except decimal.InvalidOperation: self._status = "Invalid amount" break try: decimal.Decimal(fee) except decimal.InvalidOperation: self._status = "Invalid fee" break addr_type = await api.Daemon.validate_address(self._ws, addr) if addr_type == "invalid": self._status = "Invalid address" break dests = [(addr, amount)] ec, tx_hash = await api.Wallet.send(self._ws, dests, fee=fee, pocket=self._active_pocket) if ec: self._status = ec.name else: self._status = "Sent %s" % tx_hash break elif c == curses.KEY_BACKSPACE: self._send_fields[self._selected_send_item] = \ self._send_fields[self._selected_send_item][:-1] elif c == curses.KEY_LEFT or c == curses.KEY_RIGHT: pass else: self._send_fields[self._selected_send_item] += chr(c)