def create_window(ncols, nlines, begin_x=0, begin_y=0): """Initialize curses, colors, make and return window. :param ncols: number of columns :type ncols: integer :param nlines: number of lines :type nlines: integer :param begin_x: offset by x :type begin_x: integer :param begin_y: offset by y :type begin_y: integer :return: initialized curses window :rtype: `curses.Window` """ curses.initscr() curses.start_color() if not Settings.system.no_color: init_curses_pairs(curses) # XXX: is this must be the first call of Style? Style().init_styles(curses) screen = curses.newwin(nlines, ncols, begin_x, begin_y) screen.keypad(0) screen.nodelay(1) curses.noecho() curses.cbreak() curses.curs_set(0) return screen
def main(): global screen screen = curses.initscr() init_screen() screen.refresh() curses.curs_set(0) import sys if len(sys.argv) > 1 and sys.argv[1] == "-s": screen.getch() else: while True: try: c = screen.getch() if c == ord('n'): curses.endwin() show_netinfo() screen = curses.initscr() init_screen() screen.refresh() if c == 27 : curses.endwin() return 0 except KeyboardInterrupt: pass curses.endwin()
def maze(): curses.start_color() curses.initscr() curses.init_pair(1, curses.COLOR_RED, curses.COLOR_BLACK) for i in range(8, 17): # penis screen.addstr(i, 22, "â–ˆ") for i in range(22, 27): screen.addstr(8, i, "â–ˆ") for i in range(29, 43): screen.addstr(8, i, "â–ˆ") for i in range(46, 68): screen.addstr(8, i, "â–ˆ") for i in range(22, 32): screen.addstr(17, i, "â–ˆ") for i in range(34, 50): screen.addstr(17, i, "â–ˆ") for i in range(52, 68): screen.addstr(17, i, "â–ˆ") for i in range(8, 12): screen.addstr(i, 68, "â–ˆ") for i in range(14, 18): screen.addstr(i, 68, "â–ˆ") for i in range(15, 18): screen.addstr(i, 26, "â–ˆ") for i in range(13, 18): screen.addstr(i, 36, "â–ˆ") for i in range(8, 12): screen.addstr(i, 48, "â–ˆ") for i in range(8, 12): screen.addstr(i, 61, "â–ˆ") for i in range(13, 18): screen.addstr(i, 57, "â–ˆ") for i in range(54, 58): screen.addstr(13, i, "â–ˆ")
def create_window(self, x, y, a=0, b=0): curses.initscr() curses.start_color() #user interface curses.init_pair(Color.ui_norm, curses.COLOR_WHITE, curses.COLOR_BLACK) curses.init_pair(Color.ui_yellow, curses.COLOR_YELLOW, curses.COLOR_BLACK) #damage panel curses.init_pair(Color.dp_blank, curses.COLOR_BLACK, curses.COLOR_BLACK) curses.init_pair(Color.dp_ok, curses.COLOR_WHITE, curses.COLOR_GREEN) curses.init_pair(Color.dp_middle, curses.COLOR_WHITE, curses.COLOR_YELLOW) curses.init_pair(Color.dp_critical, curses.COLOR_WHITE, curses.COLOR_RED) curses.init_pair(Color.sh_ok, curses.COLOR_WHITE, curses.COLOR_BLUE) curses.init_pair(Color.sh_mid, curses.COLOR_WHITE, curses.COLOR_CYAN) #weapons curses.init_pair(Color.blaster, curses.COLOR_GREEN, curses.COLOR_BLACK) curses.init_pair(Color.laser, curses.COLOR_BLACK, curses.COLOR_RED) curses.init_pair(Color.um, curses.COLOR_MAGENTA, curses.COLOR_BLACK) screen = curses.newwin(y, x, a, b) screen.keypad(1) screen.nodelay(1) curses.noecho() curses.cbreak() curses.curs_set(0) return screen
def test_text_effects(self): """ Check effects can be played. """ # Skip for non-Windows if the terminal definition is incomplete. # This typically means we're running inside a non-standard termina;. # For example, thi happens when embedded in PyCharm. if sys.platform != "win32": curses.initscr() if curses.tigetstr("ri") is None: self.skipTest("No valid terminal definition") # A lot of effects are just about the visual output working when played # so check that playing a load of text effects doesn't crash. # # It's really not a great test, but it's important to show Effects are # dynamically compatible with Screen.play(). def internal_checks(screen): screen.play([ Scene([ MockEffect(count=5), Print(screen, FigletText("hello"), 2), Cycle(screen, FigletText("world"), 6), BannerText(screen, FigletText("world"), 10, 3), Mirage(screen, FigletText("huh?"), 14, 2)], 0)]) Screen.wrapper(internal_checks, height=25)
def isusable(s): # Not a terminal? Can't use curses. if not sys.stdout.isatty() and sys.stdin.isatty(): return 0 # No TERM specified? Can't use curses. try: if not len(os.environ["TERM"]): return 0 except: return 0 # ncurses doesn't want to start? Can't use curses. # This test is nasty because initscr() actually EXITS on error. # grr. pid = os.fork() if pid: # parent return not os.WEXITSTATUS(os.waitpid(pid, 0)[1]) else: # child curses.initscr() curses.endwin() # If we didn't die by here, indicate success. sys.exit(0)
def makescreen(): curses.initscr() #curses.start_color() stdscr = curses.newwin(rows, cols,0,0) stdscr.keypad(1) stdscr.box() i=0
def main(): try: curses.initscr() curses.echo() #curses.noecho() curses.cbreak() editwinrows = curses.LINES - 8 topwin = outputwin(0, 0, 5, curses.COLS) edit = curses.newwin(editwinrows, curses.COLS, 5, 0); bottomwin = curses.newwin(3, curses.COLS, editwinrows + 2, 0); topwin.output("hello, world!") #topwin.addstr(0, curses.COLS/2, "hello, world!") #blank_line(topwin, 0, 0, 30) bottomwin.refresh() curline = 0 while True : topwin.output( str(curline) ) #edit.addstr( curline, 0, "hello") #edit.refresh() time.sleep(1) curline = curline + 1 except: curses.echo() curses.nocbreak() curses.endwin() traceback.print_exc()
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 lvl2(self,inv,win,fb,fl): curses.initscr() curses.start_color() curses.init_pair(1,curses.COLOR_YELLOW,curses.COLOR_BLUE) curses.init_pair(2,curses.COLOR_YELLOW,curses.COLOR_BLACK) curses.init_pair(3,curses.COLOR_YELLOW,curses.COLOR_RED) curses.init_pair(4,curses.COLOR_BLACK,curses.COLOR_GREEN) il = int(fl/3) ib = int(fb/3) i = 0 j = 1 for i in range(fl/4): win.addch(ib,j,'=',curses.color_pair(4)) win.addch(2*ib,j,'=',curses.color_pair(4)) j = j + 1 i = 0 j = 3*fl/4 for i in range(fl/4): win.addch(ib,j,'=',curses.color_pair(4)) win.addch(2*ib,j,'=',curses.color_pair(4)) j = j + 1 win.refresh() win.addstr(1,il,'\###/',curses.color_pair(4)) win.addstr(2,il,'`\#/`',curses.color_pair(4)) win.addstr(3*ib-2,2*il,'`/#\\`',curses.color_pair(4)) win.addstr(3*ib-1,2*il,'/###\\',curses.color_pair(4)) win.refresh() return win
def __init__(self): # Define all game state variables self.welcome_screen = WelcomeScreen() self.game_screen = GameScreen() self.game_over_screen = GameOverScreen() self.difficulty = Difficulty(self.setOptions) self.points = 0 self.done = False self.alert_loss = False self.settings = Settings() self.settings.set('hTime', 0.3) # Define all the Curses stuff curses.initscr() curses.start_color() curses.init_pair(1, curses.COLOR_BLACK, curses.COLOR_WHITE) curses.init_pair(2, curses.COLOR_WHITE, curses.COLOR_BLACK) curses.init_pair(3, curses.COLOR_RED, curses.COLOR_BLACK) self.screen = curses.newwin(0, 0) self.screen.keypad(1) self.screen.nodelay(1) curses.noecho() curses.cbreak() curses.curs_set(0)
def load(self,wi): curses.initscr() curses.start_color() curses.init_pair(1,curses.COLOR_YELLOW,curses.COLOR_BLUE) curses.init_pair(2,curses.COLOR_YELLOW,curses.COLOR_BLACK) curses.init_pair(3,curses.COLOR_YELLOW,curses.COLOR_RED) curses.init_pair(4,curses.COLOR_BLACK,curses.COLOR_GREEN) # wine = wi.subwin(5,35,15,55) #y,x wine = curses.newwin(5,35,15,55) #y,x wine.border('|','|','-','-','+','+','+','+') wine.addstr(2,8,'Loading') wine.bkgd(' ',curses.color_pair(4)) wine.refresh() curses.napms(400) wine.addstr(2,8,'Loading.') wine.bkgd(' ',curses.color_pair(4)) wine.refresh() curses.napms(400) wine.addstr(2,8,'Loading..') wine.bkgd(' ',curses.color_pair(4)) wine.refresh() curses.napms(400) wine.addstr(2,8,'Loading...') wine.bkgd(' ',curses.color_pair(4)) wine.refresh() curses.napms(400) wine.addstr(2,8,'Loading....') wine.bkgd(' ',curses.color_pair(4)) wine.refresh() curses.napms(1200) wine.clear() wine.refresh()
def lvl1(self,inv,win,fb,fl): curses.initscr() curses.start_color() curses.init_pair(1,curses.COLOR_YELLOW,curses.COLOR_BLUE) curses.init_pair(2,curses.COLOR_YELLOW,curses.COLOR_BLACK) curses.init_pair(3,curses.COLOR_YELLOW,curses.COLOR_RED) curses.init_pair(4,curses.COLOR_BLACK,curses.COLOR_GREEN) il = int(fl/3) ib = int(fb/3) i = 0 j = 1 for i in range(fl/4): win.addch(ib,j,'=',curses.A_REVERSE) j = j + 1 i = 0 for i in range((2*fl)/4): win.addch(2*ib,j,'=',curses.A_REVERSE) j = j + 1 i = 0 j = 3*fl/4 for i in range(fl/4): win.addch(ib,j,'=',curses.A_REVERSE) j = j + 1 win.refresh() return win
def main(): lab_components = load_map() win = curses.initscr() win = create_window(win) curses.start_color() curses.init_pair(1, curses.COLOR_BLUE, curses.COLOR_BLACK) win.bkgd(' ', curses.color_pair(1)) while True: win.addch(coord_y, coord_x, 'O') win.addstr(22, 2, 'Score : ' + str(score) + ' ') if coord_x == 69 and coord_y == 13: break event = win.getch() if event == ord("q"): break elif event == curses.KEY_LEFT: moving_left(win, lab_components) elif event == curses.KEY_RIGHT: moving_right(win, lab_components) elif event == curses.KEY_UP: moving_up(win, lab_components) elif event == curses.KEY_DOWN: moving_down(win, lab_components) evalu = score_eval() win = curses.initscr() win.clear() print("you score: " + str(score) + " " + str(evalu)) time.sleep(3) curses.endwin()
def __init__(self, height, width): self.width = width self.height = height self.address = address display_size_y = None display_size_x = None curses.initscr() curses.start_color() curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK) curses.init_pair(2, curses.COLOR_RED, curses.COLOR_BLACK) curses.noecho() curses.cbreak() curses.curs_set(0) self.window['main'] = curses.newwin(height, width / 2, 0, 0) self.window['ingress'] = curses.newwin(height / 2, width / 2, 0, width / 2) self.window['egress'] = curses.newwin(height / 2 , width / 2, height / 2, width / 2) for w in self.window: self.window[w].box(0, 1) self.set_title()
def run(self): curses.initscr() curses.start_color() curses.cbreak() curses.noecho() self.__main_win = curses.newwin(24, 80, 0, 0) self.__key_loop()
def main(stdscr): curses.initscr() curses.start_color() curses.use_default_colors() curses.cbreak() # No need for [Return] curses.noecho() # Stop keys being printed curses.curs_set(0) # Invisible cursor stdscr.keypad(True) stdscr.clear() curses.panel.update_panels() run_update_window_thread(True) update_window_thread = Thread(target = number_window_updater) update_window_thread.start() run_update_number_thread(True) update_number_thread = Thread(target = number_updater) update_number_thread.start() stdscr.addstr(5,10,"Press Q to exit.") while True: key = stdscr.getkey() if key == "q": run_update_window_thread(False) run_update_number_thread(False) sleep(0.01) quit() elif key == " ": change_count(10000)
def initialize(): curses.initscr() win = curses.newwin(24, 80, 0, 0) win.keypad(1) curses.noecho() curses.curs_set(0) win.border(0) win.nodelay(1) key = KEY_RIGHT git_handle = [] win.addstr(0, 2, ' Login ') win.addstr(0, 36, ' PARETO ') win.addstr(12, 31, ' GitHub Username: '******'\n'): y,x=curses.getsyx() #win.addstr(12, 48+len(git_handle), curses.A_REVERSE) event = win.getch() if event != -1: prevKey = key try: git_handle.append(chr(prevKey)) except: # not a printable ascii character pass key = event curses.setsyx(y,x+1) curses.doupdate() #if key == 27: # curses.endwin() curses.endwin() print "git handle:", "".join(git_handle)
def main(screen): # Setup a window object, misc curses.initscr() curses.start_color() curses.use_default_colors() curses.cbreak() # No need for [Return] curses.noecho() # Stop keys being printed curses.curs_set(0) # Invisible cursor screen.keypad(True) screen.clear() screen.border(0) # Setup color pairs curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK) curses.init_pair(2, curses.COLOR_YELLOW, curses.COLOR_BLACK) # Setup background screen.bkgd(' ', curses.color_pair(1)) # Setup constants CENTER = get_pos_consts(screen) # Execute while True: choice = startup_menu(screen, CENTER) if choice.func is not None: choice(screen)
def InitWindows(screen, args): # reset curses logger.handlers = [] curses.endwin() # set up screen curses.initscr() screen.nodelay(1) curses.start_color() curses.cbreak() curses.setsyx(-1, -1) screen.addstr("Quake Live rcon: %s" % args.host) screen.refresh() maxy, maxx = screen.getmaxyx() # set up colors for i in range(1,7): curses.init_pair(i, i, 0) # bugfix: 5 and 6 are swapped in Quake from the standard terminal colours curses.init_pair(5, 6, 0) curses.init_pair(6, 5, 0) # this window holds the log and server output begin_x = 2; width = maxx - 4 begin_y = 2; height = maxy - 5 output_window = curses.newwin(height, width, begin_y, begin_x) screen.refresh() output_window.scrollok(True) output_window.idlok(True) output_window.leaveok(True) output_window.refresh() # this window takes the user commands begin_x = 4; width = maxx - 6 begin_y = maxy - 2; height = 1 input_window = curses.newwin(height, width, begin_y, begin_x) screen.addstr(begin_y, begin_x - 2, '>') screen.refresh() input_window.idlok(True) input_window.leaveok(False) input_window.refresh() # solid divider line between input and output begin_x = 2; width = maxx - 4 begin_y = maxy - 3; height = 1 divider_window = curses.newwin(height, width, begin_y, begin_x) screen.refresh() divider_window.hline(curses.ACS_HLINE, width) divider_window.refresh() # redirect logging to the log window mh = CursesHandler(output_window) formatterDisplay = logging.Formatter('%(asctime)-8s|%(name)-12s|%(levelname)-6s|%(message)-s', '%H:%M:%S') logger.addHandler(mh) # finalize layout screen.refresh() return input_window, output_window
def restoreScreen(self): if not curses: print 'huh?' else: curses.initscr() curses.nocbreak() curses.echo() curses.endwin()
def setUp(self): # Skip for non-Windows if the terminal definition is incomplete. # This typically means we're running inside a non-standard terminal. # For example, this happens when embedded in PyCharm. if sys.platform != "win32": curses.initscr() if curses.tigetstr("ri") is None: self.skipTest("No valid terminal definition")
def start(self): debug("starting") curses.initscr() # for some reason unknown to me, this crashes macs if sys.platform != "darwin": curses.curs_set(0) curses.wrapper(self.main_loop)
def sigwinch_handler(n, frame): global stdscr curses.endwin() curses.initscr() # consume any subsequent characters awhile while 1: char = stdscr.getch() if char == -1: break
def run(params): try: import curses curses.initscr() cols = curses.COLS curses.endwin() except: cols = 80 h = HeadlessDisplayer() while 1: configdir = ConfigDir('downloadheadless') defaultsToIgnore = ['responsefile', 'url', 'priority'] configdir.setDefaults(defaults,defaultsToIgnore) configdefaults = configdir.loadConfig() defaults.append(('save_options',0, "whether to save the current options as the new default configuration " + "(only for btdownloadheadless.py)")) try: config = parse_params(params, configdefaults) except ValueError, e: print 'error: ' + str(e) + '\nrun with no args for parameter explanations' break if not config: print get_usage(defaults, 80, configdefaults) break if config['save_options']: configdir.saveConfig(config) configdir.deleteOldCacheData(config['expire_cache_data']) myid = createPeerID() seed(myid) config['overlay'] = 0 doneflag = Event() def disp_exception(text): print text rawserver = RawServer(doneflag, config['timeout_check_interval'], config['timeout'], ipv6_enable = config['ipv6_enabled'], failfunc = h.failed, errorfunc = disp_exception) upnp_type = UPnP_test(config['upnp_nat_access']) while True: try: listen_port = rawserver.find_and_bind(config['minport'], config['minport'], config['maxport'], config['bind'], ipv6_socket_style = config['ipv6_binds_v4'], upnp = upnp_type, randomizer = config['random_port']) break except socketerror, e: if upnp_type and e == UPnP_ERROR: print 'WARNING: COULD NOT FORWARD VIA UPnP' upnp_type = 0 continue print "error: Couldn't listen - " + str(e) h.failed() return
def setup_curses(self): os.environ['ESCDELAY'] = '25' # don't know a cleaner way try: self.win = curses.initscr() except _curses.error as e: if e.args[0] == "setupterm: could not find terminal": os.environ['TERM'] = 'linux' self.win = curses.initscr() self.keymaps.use_keymap('browser') DisplayableContainer.__init__(self, None)
def setup_curses(self): os.environ["ESCDELAY"] = "25" # don't know a cleaner way try: self.win = curses.initscr() except _curses.error as e: if e.args[0] == "setupterm: could not find terminal": os.environ["TERM"] = "linux" self.win = curses.initscr() self.keymaps.use_keymap("browser") DisplayableContainer.__init__(self, None)
def main(stdscr): curses.curs_set(0) curses.start_color() curses.initscr() # Create windows for log (lines 1-3), map (lines 4-20) and stats (lines 21-24). log_window = curses.newwin(3, 79, 0, 1) map_window = curses.newwin(17, 79, 3, 1) stat_window = curses.newwin(4, 79, 20, 1) dungeon = Dungeon() dungeon.create_item(7, 9, "ring") dungeon.create_item(10, 12, "ring") dungeon.create_item(20, 10, "potion") player = Player() state = Basic(stdscr, log_window, map_window, stat_window, dungeon, player) new_state = None while 1: window_size = stdscr.getmaxyx() # Check if the terminal size is botched - refactor when you understand curses better if window_size[0] < 24 or window_size[1] < 80: state = create_state("termresize", stdscr, log_window, map_window, stat_window, dungeon, player) state.draw() curses.doupdate() c = stdscr.getch() else: # Cargoculted on Monday morning, 05:00. # Not doing this initscr() will result in a black screen before first keypress when moving # to a new state. No idea what causes this. Will do for now. if new_state is not None: curses.initscr() state.draw() curses.doupdate() c = stdscr.getch() new_state = state.handle_input(c) if new_state is not None: if new_state == "quit" : break else: state = create_state(new_state, stdscr, log_window, map_window, stat_window, dungeon, player) stdscr.erase()
def init(): # on initialise la fenetre curses curses.initscr() win = curses.newwin(30, 80, 0, 0) curses.noecho() curses.curs_set(0) win.nodelay(1) logging.basicConfig(filename='snake.log', level=logging.INFO) # creation du niveau level = Level.create(1, 'levels.txt') # creation du snake snake = Snake.create(35, 15, 1, 2) # creation du food food = None # creation du menu menu = Menu.create( 'Change name', 'Change difficulty', 'Select level', 'Show HighScores', 'Play', 'Quit game' ) # definition de l'etat du programme state = 'menu' # definition du nom du joueur name = 'player1' # definition de la difficulte difficulty = 2 score = -1 HighScoreTable = HighScores.get() # creation de la variable de type game game = Game.create( menu, level, snake, food, win, state, name, difficulty, score, HighScoreTable ) return game
def init(): # on initialise la fenetre curses curses.initscr() win = curses.newwin(30, 80, 0, 0) curses.noecho() curses.curs_set(0) win.nodelay(0) curses.curs_set(1) win.move(10, 10) return win
def play_func(stdscr): stdscr = curses.initscr() curses.resize_term(height, width) curses.curs_set(0) next_step = 0 prev_step = 0 pos = [[height//2, width//2]] rand_piece = 0 # position of the piece to collect stdscr.timeout(speed*10) while next_step != 'q': # if 'q' button was pressed quit the game # randomly select position of the piece to collect while True: if rand_piece and rand_piece not in pos: break rand_piece = [ random.randint(0, height-1), random.randint(0, width-1) ] # clear the screen and print your snake and piece stdscr.clear() for coord in pos: stdscr.addstr(*coord, '*') stdscr.addstr(*rand_piece, '*') stdscr.refresh() # as .getkey() function throws an exception if there is no input - use # previous value if there is not input try: next_step = stdscr.getkey() except Exception: next_step = prev_step x = pos[-1][1] y = pos[-1][0] # check if pressed key within accepted accepted keys and range of values if next_step not in ('KEY_UP', 'KEY_DOWN', 'KEY_RIGHT', 'KEY_LEFT'): continue # check if next position if within the window range and change the values # to support transition between borders if next_step == 'KEY_UP': y = y - 1 if y > 0 else height - 1 elif next_step == 'KEY_DOWN': y = y + 1 if y < height - 1 else 0 elif next_step == 'KEY_RIGHT': x = x + 1 if x < width - 1 else 0 elif next_step == 'KEY_LEFT': x = x - 1 if x > 0 else width - 1 # end the game if snake crashed in itself if [y, x] in pos: print(f'The game is over! Your score: {len(pos)}!') break # if piece is collected set piece coordinates to 0 and continue # else remove first value from list of coordinated to make snake move if rand_piece == [y, x]: rand_piece = 0 else: pos.pop(0) # add next step to list of coordinate to move snake forward pos.append([y, x]) prev_step = next_step
# INSTRUCTIONS: - UP, RIGHT, DOWN, LEFT, ARROWS TO PLAY # - 'SPACEBAR' TO PAUSE / RESUME # - PRESS 'ESC' BUTTON WHILE THE IS CURSER MOVING TO QUIT. WILL NOT ESCAPE IF PAUSED. # - HAVE FUN!! It's even more breaking down the code and understanding it all! :) # # UPDATE: Corrected my comments to reflect python syntax. No more "array". import curses from curses import KEY_RIGHT, KEY_LEFT, KEY_UP, KEY_DOWN, A_BOLD, A_UNDERLINE from random import randint print( KEY_UP, KEY_RIGHT, KEY_DOWN, KEY_LEFT ) # Put this print statement so you can see what these values are in case you don't want to go look for them. Will print after the game ends. curses.initscr() # This is the initialization of the terminal window. win = curses.newwin(50, 120, 5, 10) # This will size the window to what you want. win.attron(A_BOLD) # Makes the message "snake attack!" in bold lettering win.addstr( 15, 25, 'Snake attack!' ) # Just a fun message, immediately eaten by the snake when it starts. It doesn't add body to the snake win.attroff(A_BOLD) # Ends the bold lettering for "snake attack!" win.keypad(1) # Keep 1. 1 = yes. 0 = no. curses.noecho() curses.curs_set(0) # Curser 0 = invis. 1 = visible. 2 = very freakin visible. win.nodelay(1) # Why is this not making a difference? key = KEY_RIGHT # Assigning value for key score = 0 # Assigning value to score count = 0
def __enter__(self): self.stdscr = curses.initscr() return self
def form_groups(self): try: # Start curses stdscr = curses.initscr() curses.noecho() curses.cbreak() stdscr.keypad(True) curses.start_color() curses.use_default_colors() curses.init_pair(1, curses.COLOR_RED, -1) #curses.COLOR_BLACK) curses.init_pair(2, 14, -1) #curses.COLOR_BLACK) curses.init_pair(3, curses.COLOR_GREEN, -1) #curses.COLOR_BLACK) groups = {} ungrouped = list(range(len(self.answers))) # Begin loop text = "" g_tmp = {} g_off = 0 while True: valid = False if "quit".startswith(text) or "exit".startswith(text): valid = True g_tmp = self.validate_command(text, groups, ungrouped) if g_tmp != False: valid = True else: g_tmp = {} y, x = self.draw_screen(stdscr, groups, ungrouped, text, valid, g_tmp, g_off) # Get input c = stdscr.getch(y, x) if ord(' ') <= c <= ord('~'): text += chr(c) elif c in [8, 127, curses.KEY_BACKSPACE] and len(text) > 0: text = text[:-1] elif c in [10, 13, curses.KEY_ENTER]: if "quit".startswith(text) or "exit".startswith(text): break if self.process_command(text, groups, ungrouped): g_tmp = {} text = "" elif c == 260: # left if g_off > 0: g_off -= 1 elif c == 261: # right if g_off < len(groups) - 1: g_off += 1 finally: # save groups filename = self.save_groups(groups, ungrouped) # Terminate curses curses.nocbreak() stdscr.keypad(False) curses.echo() curses.endwin() print(f"Session saved in {filename}")
def right(): GPIO.output(17, 1) GPIO.output(18, 0) GPIO.output(22, 0) GPIO.output(23, 1) def stop(): GPIO.output(17, 0) GPIO.output(18, 0) GPIO.output(22, 0) GPIO.output(23, 0) shell = curses.initscr() shell.nodelay(False) while True: key = shell.getch() if key == 119: print("Forward") forwards() elif key == 115: print("Backward") backwards() elif key == 97: print("Left")
def __init__( self, web_port=26000, window_height=40, window_width=130, auto_scoll=True, max_log_lines=500, wait_on_quit=True, min_refresh_rate=1000, bytes_to_str=DEFAULT_HEX_TO_STR, ): """ :type web_port: int :param web_port: Webinterface port. Default 26000 :type window_height: int :param window_height: Default console heigth, set to on startup. Default 40 :type window_width: int :param window_width: Default console width, set to on startup. Default 130 :type auto_scoll: bool :param auto_scoll: Whether to auto-scoll the cases and crashed windows to allways display the last line if there are too many lines to display all of them. Default True :type max_log_lines: int :param max_log_lines: Maximum log lines to keep in the internal storage. Additional lines exceeding this limit will not be displayed. Default 500 :type wait_on_quit: bool :param wait_on_quit: Whether to keep the GUI open and wait for user-input when the main thread is about to exit. Default True :type min_refresh_rate: int :param min_refresh_rate: The delay between two checks for a resize of the terminal in milliseconds. Increment 100 ms. Default 1000 ms :type bytes_to_str: function :param bytes_to_str: Function that converts sent/received bytes data to string for logging. """ self._title = "boofuzz" self._web_port = web_port self._max_log_lines = max_log_lines self._auto_scroll = auto_scoll self._current_data = None self._log_storage = [] self._fail_storage = [] self._wait_on_quit = wait_on_quit self._quit = False self._status = 0 # 0: Running 1: Paused 2: Done self._refresh_interval = min_refresh_rate self._event_resize = True self._event_log = False self._event_case_close = False self._event_crash = False self._total_index = 0 self._total_num_mutations = 0 self._current_name = "" self._current_index = 0 self._current_num_mutations = 0 self._format_raw_bytes = bytes_to_str self._version = helpers.get_boofuzz_version(helpers) # Resize console to minimum size self._width, self._height = get_terminal_size() if self._height < window_height or self._width < window_width: print("\x1b[8;{};{}t".format(window_height, window_width)) self._height, self._width = window_height, window_width self._height_old = 0 self._width_old = 0 self._min_size_ok = True self._stdscr = curses.initscr() curses.start_color() curses.use_default_colors() curses.noecho() curses.curs_set(0) self._stdscr.nodelay(1) # Curses color pairs curses.init_pair(1, curses.COLOR_WHITE, -1) curses.init_pair(2, curses.COLOR_CYAN, -1) curses.init_pair(3, curses.COLOR_RED, -1) curses.init_pair(4, curses.COLOR_YELLOW, -1) curses.init_pair(5, curses.COLOR_GREEN, -1) curses.init_pair(6, curses.COLOR_MAGENTA, -1) curses.init_pair(7, curses.COLOR_BLACK, curses.COLOR_WHITE) # Start thread and restore the original SIGWINCH handler self._draw_thread = threading.Thread(name="curses_logger", target=self._draw_screen) current_signal_handler = signal.getsignal(signal.SIGWINCH) self._draw_thread.start() signal.signal(signal.SIGWINCH, current_signal_handler)
# This script calculates the distance between an HC-SR04 module and the nearest object. # It is capable of handling multiple modules simultaneously. # # version: 1.0 (30.12.2019) import RPi.GPIO as GPIO import time import curses # keyboard input and interface screen = curses.initscr() # create new screen screen.nodelay(True) # .getch() is ignored if no keyboard input is detected curses.noecho() # do not ECHO_1 keyboard input curses.cbreak() # disable return-press for input screen.keypad(True) # enable special-keys GPIO.setmode(GPIO.BCM) # set GPIO mode TRIG_1 = 18 # trigger pin of HC-SR04 module(front) TRIG_2 = 23 # trigger pin of HC-SR04 module(side) TRIG_3 = 25 # trigger pin of HC-SR04 module(back) TRIG_4 = 24 # trigger pin of HC-SR04 module(back-angled) ECHO_1 = 4 # echo pin of HC-SR04 module(front) ECHO_2 = 17 # echo pin of HC-SR04 module(side) ECHO_3 = 22 # echo pin of HC-SR04 module(back) ECHO_4 = 27 # echo pin of HC-SR04 module(back-angled) # define all trigger pins as outputs and all echo pins as inputs # make sure all pins ar free to use to avoid data collision GPIO.setup(TRIG_1, GPIO.OUT) GPIO.setup(ECHO_1, GPIO.IN) GPIO.setup(TRIG_2, GPIO.OUT)
# Prevent current fan speeds below minimum from staying there a = setFanSpeed(min_speed) if not args.dynamic_printing: print("Control+C to quit\n") print("Detected %i GPUs" % (len(a.cards)), '\n') def update_curses(gpu_idx, temp, temp_diff, fan_rpm, fan_pct): pass while True: a.set_all_fan_speeds(tempgoal=tempgoal) time.sleep(time_between_fan_check) exit() window = curses.initscr() curses.noecho() curses.cbreak() curses.curs_set(0) # Hide cursor max_screen = tuple(numpy.subtract(window.getmaxyx(), (1, 1))) def make_curses_coords(): global window curses_positions = {} init_x = 0 init_y = 5 width = 45 height = 6
def run_curses_app(): stdscr = curses.initscr() stdscr.refresh() stdscr.keypad(True) curses.start_color() curses.use_default_colors() curses.curs_set(0) curses.noecho() themes = {s.name: s for s in get_themes(BASE16_SCRIPTS_DIR)} scroll_list_cols = 35 preview_cols = 42 total_cols = scroll_list_cols + preview_cols scroll_list_win = ScrollListWindow(NUM_COLORS, scroll_list_cols) preview_win = PreviewWindow(NUM_COLORS, preview_cols, 0, scroll_list_cols) preview_win.render() scroll_list_win.set_data(sorted(themes.keys())) scroll_list_win.render() themes[scroll_list_win.value].run_script() while True: scroll_list_win.render() preview_win.render() c = stdscr.getch() if c == curses.KEY_DOWN: scroll_list_win.down() themes[scroll_list_win.value].run_script() elif c == curses.KEY_UP: scroll_list_win.up() themes[scroll_list_win.value].run_script() elif c == curses.KEY_PPAGE: scroll_list_win.up_page() themes[scroll_list_win.value].run_script() elif c == curses.KEY_NPAGE: scroll_list_win.down_page() themes[scroll_list_win.value].run_script() elif c == curses.KEY_HOME: scroll_list_win.top() themes[scroll_list_win.value].run_script() elif c == curses.KEY_END: scroll_list_win.bottom() themes[scroll_list_win.value].run_script() elif c == ord('q'): end_run() elif c == ord('\n'): theme = themes[scroll_list_win.value] theme.run_alias() end_run(theme) elif c == curses.KEY_RESIZE: if curses.LINES < NUM_COLORS: raise ValueError('Terminal has less than 22 lines.') elif curses.COLS < total_cols: raise ValueError( 'Terminal has less than {} cols.'.format(total_cols))
import math import numpy import curses # Student = [] StudentID = [] Course = [] CourseID = [] Mark = [] Credit = [] gpa = [] MarkGPA = [] print("Magic things about to happen....") screen = curses.initscr() print("Approved") screen.refresh() curses.napms(3000) curses.endwin() print("Ended") class Students: def __init__(self, id, name, dob): self.__id = id self.__name = name self.__dob = dob Student.append(self) StudentID.append(self.__id)
import curses stdscr = curses.initscr() curses.noecho() curses.cbreak() stdscr.keypad(True) stdscr.addstr(5, 10, "hello") stdscr.refresh() for i in range(10): stdscr.getch() curses.echo() curses.nocbreak() stdscr.keypad(False) curses.endwin()
import curses from curses import KEY_RIGHT, KEY_LEFT, KEY_UP, KEY_DOWN from random import randint curses.initscr() win = curses.newwin(20, 60, 0, 0) win.keypad(1) curses.noecho() curses.curs_set(0) win.border(0) win.nodelay(1) key = KEY_RIGHT score = 0 flag = True # True for right, Falsefor left airship = [[14,10], [14, 9], [14,8],[13,9]] bullets =[] target =[10, 20] win.addch(target[0], target[1], '*') while key!= 27: win.border(0) win.addstr(0, 2, 'Score: ' + str(score)+' ') win.addstr(0,27, 'TEST') win.timeout(150 - (len(airship)/5 + len(airship)/10)%120) # Increases the speed of Snake as its length increases prevKey = key key = win.getch() # Previous key pressed #event = win.getch() #key = key if event == -1 else event
# Falling Matrix effect in Unix/Linux terminal # Note: pycurses and a colored terminal is required. # Import libraries and init import curses import random import time import sys SCREEN = curses.initscr() HEIGHT, WIDTH = SCREEN.getmaxyx() # Define colors curses.start_color() curses.init_pair(1, 219, curses.COLOR_BLACK) curses.init_pair(2, 125, curses.COLOR_BLACK) curses.init_pair(3, 229, curses.COLOR_BLACK) curses.init_pair(4, 136, curses.COLOR_BLACK) curses.init_pair(5, 255, curses.COLOR_BLACK) curses.init_pair(6, 240, curses.COLOR_BLACK) COLOR_THEMES = { "red":[ curses.color_pair(1), # Light curses.color_pair(2) # Dark ], "gold":[ curses.color_pair(3), # Light curses.color_pair(4) # Dark ],
def main(argv): """If this file is the main, create an instance of EstopNoGui and wait for user to terminate. This has little practical use, because calling the function this way does not give the user any way to trigger an estop from the terminal. """ parser = argparse.ArgumentParser() bosdyn.client.util.add_common_arguments(parser) parser.add_argument('-t', '--timeout', type=float, default=5, help='Timeout in seconds') options = parser.parse_args(argv) # Create robot object sdk = bosdyn.client.create_standard_sdk('estop_nogui') robot = sdk.create_robot(options.hostname) robot.authenticate(options.username, options.password) # Create estop client for the robot estop_client = robot.ensure_client(EstopClient.default_service_name) # Create nogui estop estop_nogui = EstopNoGui(estop_client, options.timeout, "Estop NoGUI") # Create robot state client for the robot state_client = robot.ensure_client(RobotStateClient.default_service_name) # Initialize curses screen display stdscr = curses.initscr() def cleanup_example(msg): """Shut down curses and exit the program.""" print('Exiting') #pylint: disable=unused-argument estop_nogui.estop_keep_alive.shutdown() # Clean up and close curses stdscr.keypad(False) curses.echo() stdscr.nodelay(False) curses.endwin() print(msg) def clean_exit(msg=''): cleanup_example(msg) exit(0) def sigint_handler(sig, frame): """Exit the application on interrupt.""" clean_exit() def run_example(): """Run the actual example with the curses screen display""" # Set up curses screen display to monitor for stop request curses.noecho() stdscr.keypad(True) stdscr.nodelay(True) curses.start_color() curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK) curses.init_pair(2, curses.COLOR_YELLOW, curses.COLOR_BLACK) curses.init_pair(3, curses.COLOR_RED, curses.COLOR_BLACK) # If terminal cannot handle colors, do not proceed if not curses.has_colors(): return # Curses eats Ctrl-C keyboard input, but keep a SIGINT handler around for # explicit kill signals outside of the program. signal.signal(signal.SIGINT, sigint_handler) # Clear screen stdscr.clear() # Display usage instructions in terminal stdscr.addstr('Estop w/o GUI running.\n') stdscr.addstr('\n') stdscr.addstr('[q] or [Ctrl-C]: Quit\n', curses.color_pair(2)) stdscr.addstr('[SPACE]: Trigger estop\n', curses.color_pair(2)) stdscr.addstr('[r]: Release estop\n', curses.color_pair(2)) stdscr.addstr('[s]: Settle then cut estop\n', curses.color_pair(2)) # Monitor estop until user exits while True: # Retrieve user input (non-blocking) c = stdscr.getch() try: if c == ord(' '): estop_nogui.stop() if c == ord('r'): estop_nogui.allow() if c == ord('q') or c == 3: clean_exit('Exit on user input') if c == ord('s'): estop_nogui.settle_then_cut() # If the user attempts to toggle estop without valid endpoint except bosdyn.client.estop.EndpointUnknownError: clean_exit("This estop endpoint no longer valid. Exiting...") # Check if robot is estopped by any estops estop_status = 'NOT_STOPPED\n' estop_status_color = curses.color_pair(1) state = state_client.get_robot_state() estop_states = state.estop_states for estop_state in estop_states: state_str = estop_state.State.Name(estop_state.state) if state_str == 'STATE_ESTOPPED': estop_status = 'STOPPED\n' estop_status_color = curses.color_pair(3) break elif state_str == 'STATE_UNKNOWN': estop_status = 'ERROR\n' estop_status_color = curses.color_pair(3) elif state_str == 'STATE_NOT_ESTOPPED': pass else: # Unknown estop status clean_exit() # Display current estop status if not estop_nogui.estop_keep_alive.status_queue.empty(): latest_status = estop_nogui.estop_keep_alive.status_queue.get( )[1].strip() if latest_status != '': # If you lose this estop endpoint, report it to user stdscr.addstr(7, 0, latest_status, curses.color_pair(3)) stdscr.addstr(6, 0, estop_status, estop_status_color) # Slow down loop time.sleep(0.5) # Run all curses code in a try so we can cleanly exit if something goes wrong try: run_example() except Exception as e: cleanup_example(e) raise e
import curses import time import random startlength = 5 growlength = 1 speed = {'Easy': 0.1, 'Medium': 0.06, 'Hard': 0.04} difficulty = 'Medium' accelration = True screen = curses.initscr() # initialise the screen screen.keypad(1) #take input from keyboard h, w = screen.getmaxyx() #the screen dimensions def game(): screen.clear() #clear the screen in the start curses.start_color() #black background curses.curs_set(0) # cursor visibility zero curses.noecho() #does not echo the keys pressed screen.border() # sets a border screen.nodelay(1) # so we dont have to wait for anything to happen head = [random.randrange(1, h - 1), random.randrange(1, w - 1)] body = [head[:]] * startlength gameover = False direction = 0 # 0: right, 1: down, 2: left, 3: up q = 0 deadcell = body[-1][:] foodmade = False while not gameover:
26 def getBuzzers(): 27 while 1: 28 if GPIO.input ( 4 ) == GPIO.LOW: 29 return 1 30 break 31 if GPIO.input ( 18 ) == GPIO.LOW: 32 return 2 33 break 34 if GPIO.input ( 22 ) == GPIO.LOW: 35 return 3 36 break 37 if GPIO.input ( 23 ) == GPIO.LOW: 38 return 4 39 break 40 if GPIO.input ( 25 ) == GPIO.LOW: 41 return 5 42 break 43 44 45 pygame.display.init() 46 screen = pygame.display.set_mode ( ( 1680 , 1050 ) ) 47 48 terminal = curses.initscr() 49 curses.cbreak() 50 terminal.nodelay ( 1 ) 51 52 terminal.addstr ( 5 , 5 , "Trivia Buzzers and Scoring" ) 53 terminal.addstr ( 7 , 5 , " 1 - 5 -- Show team as buzzed in" ) 54 terminal.addstr ( 8 , 5 , " r -- Reset buzzers" ) 55 terminal.addstr ( 10 , 5 , " b -- enable buzzers" ) 56 terminal.addstr ( 11 , 5 , " x -- Exit (Careful, no confirmation)" ) 57 58 numbers = list() 59 left = 0 60 numbers.append ( ( pygame.image.load ( "numbers_01.jpg" ) , left ) ) 61 left += numbers [ 0 ] [ 0 ].get_width() 62 numbers.append ( ( pygame.image.load ( "numbers_02.jpg" ) , left ) ) 63 left += numbers [ 1 ] [ 0 ].get_width() 64 numbers.append ( ( pygame.image.load ( "numbers_03.jpg" ) , left ) ) 65 left += numbers [ 2 ] [ 0 ].get_width() 66 numbers.append ( ( pygame.image.load ( "numbers_04.jpg" ) , left ) ) 67 left += numbers [ 3 ] [ 0 ].get_width() 68 numbers.append ( ( pygame.image.load ( "numbers_05.jpg" ) , left ) ) 69 70 running = True 71 while running == True: 72 choice = terminal.getch ( 12 , 5 ) 73 if choice == -1: continue 74 if choice == ord ( "1" ): 75 showWinner ( 1 ) 76 elif choice == ord ( "2" ): 77 showWinner ( 2 ) 78 elif choice == ord ( "3" ): 79 showWinner ( 3 ) 80 elif choice == ord ( "4" ): 81 showWinner ( 4 ) 82 elif choice == ord ( "5" ): 83 showWinner ( 5 ) 84 85 elif choice == ord ( "b" ): 86 showWinner ( getBuzzers() ) 87 88 elif choice == ord ( "r" ): 89 reset() 90 elif choice == ord ( "x" ): 91 running = False 92 93 curses.endwin()
def terminal_dimensions(): return curses.initscr().getmaxyx()
def draw_menu(stdscr): global tui_klub_id k = 0 cursor_x = 0 cursor_y = 0 encoding = locale.getpreferredencoding() locale.setlocale(locale.LC_ALL, '') stdscr = curses.initscr() # Clear and refresh the screen for a blank canvas stdscr.clear() stdscr.refresh() # Start colors in curses curses.start_color() curses.init_pair(1, curses.COLOR_CYAN, curses.COLOR_BLACK) curses.init_pair(2, curses.COLOR_RED, curses.COLOR_BLACK) curses.init_pair(3, curses.COLOR_BLACK, curses.COLOR_WHITE) klub_strana = 1 # Loop where k is the last character pressed while (k != ord('q')): # RODICOVSKY ZAMEK rodzam = getParentalLockStatus() #print(str(rodzam)) if (rodzam == 1): rodzamkl = getParentalLockClub() conyxDBLast(rodzamkl) tui_klub_id = rodzamkl # Initialization stdscr.clear() height, width = stdscr.getmaxyx() tui_klub_id = getLastVisitedClub() club_changed = 0 if rodzam == 1: if k == ord("0"): # k - konfigurace tuiConfig() elif k == ord("c") or k == ord("\n"): # C - cti prispevky zobrazDiskuzi(str(tui_klub_id), stdscr, 1) stdscr.clear() elif k == ord("p"): # P - pis try: stdscr.refresh() curses.cbreak() stdscr.addstr( 0, 3, "Tvuj novy prispevek: [ ctrl+g nebo zaplneni okenka pro odeslani ]" ) height, width = stdscr.getmaxyx() x = 2 y = 2 h = height - y w = width - x rectangle(stdscr, x - 1, y - 1, h + 1, w) editwin = curses.newwin(h - 1, w - 2, x, y) stdscr.refresh() #box=Textbox(editwin) box = inputBox(editwin) box.edit() text = box.gather() try: if (text != ""): text = text[:-1] curses.nocbreak() orig_text = text tmp = orig_text.strip().split('\n') text = "" for i in tmp: text += i if (len(i) != width - 4): text += '\n' nazev_klubu = nactiNazevKlubu(tui_klub_id)[:width - 1] if (nyx_send_message(tui_klub_id, text) == 0): stdscr.addstr(0, 0, " " * width) stdscr.addstr( 0, 0, "*** Prispevek odeslan do klubu: " + sutf8(str(tui_klub_id)) + " " + nazev_klubu) else: stdscr.addstr(0, 0, " " * width) stdscr.addstr( 0, 0, "! Chyba pri odesilani prispevku do klubu" + nazev_klubu) #stdscr.getch() x = ugetch(stdscr) curses.cbreak() except Exception: stdscr.addstr(0, 0, "Nepodarilo se odeslat prispevek") #traceback.print_exc(file=sys.stdout) #stdscr.getch() x = ugetch(stdscr) stdscr.refresh() stdscr.clear() except Exception: traceback.print_exc(file=sys.stdout) input("Zmackni Enter ...") print("Problem pri ziskani cisla klubu.") else: if k == curses.KEY_DOWN: cursor_y = cursor_y + 1 elif k == ord("0"): # k - konfigurace tuiConfig() elif k == ord("1"): # 1 - napoveda tuiFile("napoveda.txt") elif k == ord("m"): # m - ozna(m)eni curses.endwin() nyx_feed_notices() stdscr.clear() elif k == curses.KEY_UP: cursor_y = cursor_y - 1 elif k == curses.KEY_RIGHT: cursor_x = cursor_x + 1 elif k == curses.KEY_LEFT: cursor_x = cursor_x - 1 elif k == ord("z"): # Z - zmeny try: tuiFile("CHANGELOG") except Exception: print("Nemuzu zobrazit seznam zmen.") elif k == ord("n"): # N - neprectene kluby retVal = tuiMainMenu(1) if (retVal): tui_klub_id = retVal conyxDBLast(tui_klub_id) club_changed = 1 klub_strana = 1 stdscr.clear() elif k == ord("r"): # R - kluby s reakci retVal = tuiMainMenu(2) if (retVal): tui_klub_id = retVal conyxDBLast(tui_klub_id) club_changed = 1 klub_strana = 1 stdscr.clear() elif k == ord("h"): # H - historie retVal = tuiMainMenu(4) #retVal=nyx_bookmarks_history() if (retVal): tui_klub_id = retVal conyxDBLast(tui_klub_id) club_changed = 1 klub_strana = 1 stdscr.clear() elif k == ord("s"): # S - sledovane retVal = tuiMainMenu(0) if (retVal): tui_klub_id = retVal conyxDBLast(tui_klub_id) club_changed = 1 stdscr.clear() elif k == ord("c") or k == ord("\n"): # C - cti prispevky zobrazDiskuzi(str(tui_klub_id), stdscr, 1) stdscr.clear() elif k == ord("o"): # O - cti predchozi od nejstarsiho prispevku res = conyxDBQuery( 'select min(id_prispevek) prid from prispevek_cache') ret = zobrazDiskuzi(str(tui_klub_id), stdscr, 1, res[1][0][0], "older") res_aft = conyxDBQuery( 'select min(id_prispevek) prid from prispevek_cache') if (res != res_aft): klub_strana += 1 stdscr.clear() elif k == ord("w"): # W - vyhledej writeup na celem Nyxu stdscr.addstr(0, 1, "Hledej na celem Nyxu:") footer = "-=[ klavesy: CTRL+G odeslat, CTRL+X zrusit ]=-" if (len(footer) >= height - 1): footer = "-=[ ^G, ^X ]=-" stdscr.addstr(height - 1, 0, footer) x = 1 y = 1 h = height - 3 w = width - 3 rectangle(stdscr, y, x, y + h, x + w) editwin = curses.newwin(h - 1, w - 1, y + 1, x + 1) stdscr.refresh() #box=Textbox(editwin) box = inputBox(editwin) box.edit() text = box.gather() if text != "": #print("TEXT: "+text) #stdscr.getch() rx, res = nyx_search_writeups(None, text, None) buffer = [] for i in res["data"]: buffer.append(i["klub_jmeno"] + "|" + i["nick"] + "|" + cleanhtml(i["content"])) tuiBuffer("Vysledek hledani", buffer) else: stdscr.clear() elif k == ord("v"): # V - vyhledat klicove slovo stdscr.addstr(0, 1, "Hledej v diskuzi:") footer = "-=[ klavesy: CTRL+G odeslat, CTRL+X zrusit ]=-" if (len(footer) >= height - 1): footer = "-=[ ^G, ^X ]=-" stdscr.addstr(height - 1, 0, footer) x = 1 y = 1 h = height - 3 w = width - 3 rectangle(stdscr, y, x, y + h, x + w) editwin = curses.newwin(h - 1, w - 1, y + 1, x + 1) stdscr.refresh() box = inputBox(editwin) box.edit() text = box.gather() if text is not None and text != "": ret = zobrazDiskuzi(str(tui_klub_id), stdscr, 1, None, None, None, text) stdscr.clear() elif k == ord("l"): # B - vyhledat prispevky uzivatele stdscr.addstr(0, 1, "Hledej prispevky uzivatele:") footer = "-=[ klavesy: CTRL+G odeslat, CTRL+X zrusit ]=-" if (len(footer) >= height - 1): footer = "-=[ ^G, ^X ]=-" stdscr.addstr(height - 1, 0, footer) x = 1 y = 1 h = height - 3 w = width - 3 rectangle(stdscr, y, x, y + h, x + w) editwin = curses.newwin(h - 1, w - 1, y + 1, x + 1) stdscr.refresh() #box=Textbox(editwin) box = inputBox(editwin) box.edit() text = box.gather() if text != "": ret = zobrazDiskuzi(str(tui_klub_id), stdscr, 1, None, None, text) stdscr.clear() elif k == ord( "e"): # U - cti nasledujici od nejnovejsiho prispevku res = conyxDBQuery( 'select max(id_prispevek) prid from prispevek_cache') ret = zobrazDiskuzi(str(tui_klub_id), stdscr, 1, res[1][0][0], "newer") if (klub_strana > 1): klub_strana -= 1 stdscr.clear() elif k == ord("p"): # P - pis tuiWritePost(stdscr, width, height, tui_klub_id) elif k == ord("i"): # I - informace ze zahlavi klubu retVal = nyx_disc_header_desc(str(tui_klub_id)) if (retVal): linelen = width - 1 stdscr.addstr( 0, 0, sutf8(cleanHtml( nactiNazevKlubu(tui_klub_id)))[:linelen], curses.color_pair(1)) lineno = 0 for i in range(0, len(retVal[0]), linelen): stdscr.addstr( lineno + 1, 0, sutf8(cleanHtml(retVal[0]))[i:(i + linelen)]) lineno += 1 if lineno > height - 2: break stdscr.addstr(height - 1, 0, "-=[ q - zpatky ]=-") else: stdscr.addstr(0, 0, sutf8("Bez zahlavi")) stdscr.refresh() #stdscr.getch() ugetch(stdscr) stdscr.clear() elif k == ord("f"): # F - odesli soubor dir = str(getConfig('soubory')[0][0]) strings = ls(dir, '') sel = fBrowser(strings, 0, 0) if (not (sel is None)): stdscr.refresh() curses.cbreak() header = "Text k souboru:" height, width = stdscr.getmaxyx() footer = "-=[ klavesy: CTRL+G odeslat, CTRL+X zrusit ]=-" if len(footer) >= width - 1: footer = "-=[ ^G, ^X, ALT+1 ]=-" stdscr.addstr(0, 2, header) stdscr.addstr(height - 1, 0, footer) x = 2 y = 2 h = height - y w = width - x rectangle(stdscr, y - 1, x - 1, h, w) editwin = curses.newwin(h - 1 - 1, w - 2, y, x) stdscr.refresh() box = inputBox(editwin) text = box.edit() stdscr.clear() nazev_klubu = nactiNazevKlubu(tui_klub_id)[:width - 1] if (nyx_send_message(tui_klub_id, text, sel) == 0): stdscr.addstr(0, 0, " " * width) stdscr.addstr( 0, 0, "*** Prispevek se souborem odeslan do klubu: " + sutf8(str(tui_klub_id)) + " " + nazev_klubu) else: stdscr.addstr(0, 0, " " * width) stdscr.addstr( 0, 0, "! Chyba pri odesilani prispevku se souborem do klubu " + nazev_klubu) stdscr.refresh() x = ugetch(stdscr) elif k == ord("d"): # D - dopisy tuiMail() elif k == ord("k"): # K - klub try: stdscr.refresh() curses.cbreak() stdscr.addstr(1, 3, "Vyber klub (cislo):") stdscr.addstr(height - 1, 0, "-=[ klavesy: CTRL+G, CTRL+X ]=-") x = 4 y = 4 h = 1 w = 12 rectangle(stdscr, x - 1, y - 1, h + x + 1, w + y + 1) editwin = curses.newwin(h, w, x, y) stdscr.refresh() #box=Textbox(editwin) box = inputBox(editwin) box.edit() text = box.gather() try: if (text != ""): tui_klub_id = int(text) conyxDBLast(tui_klub_id) conyxDBSetForumLast(tui_klub_id) except Exception: stdscr.addstr(0, 0, "Neplatny vyber klubu") traceback.print_exc(file=sys.stdout) #stdscr.getch() ugetch(stdscr) klub_strana = 1 stdscr.refresh() stdscr.clear() except Exception: traceback.print_exc(file=sys.stdout) input("Zmackni Enter ...") print("Problem pri ziskani cisla klubu.") rodzam = getParentalLockStatus() stdscr.refresh() stdscr.clear() cursor_x = max(0, cursor_x) cursor_x = min(width - 1, cursor_x) cursor_y = max(0, cursor_y) cursor_y = min(height - 1, cursor_y) # Declaration of strings start_y = int((height // 2) - 8) if (rodzam == 1): title = "klávesa c - čti" start_x_title = int((width // 2) - (len(title) // 2) - len(title) % 2) stdscr.addstr(start_y, start_x_title, sutf8(title)) subtitle = "klávesa p - piš" stdscr.addstr(start_y + 2, start_x_title, sutf8(subtitle)) else: title = "C O N Y X"[:width - 1] subtitle = "CONSOLE NYX CLIENT"[:width - 1] #keystr = "Posledni klavesa: {}".format(k)[:width-1] + " KLUB: " + str(tui_klub_id) + " str.: " + str(klub_strana) keystr = " KLUB [" + str(klub_strana) + "] : " + str(tui_klub_id) nazev_klubu = nactiNazevKlubu(tui_klub_id)[:width - 1] pre_sbar = "(q)uit |" post_sbar = "| (1) napoveda" fill_len = width - 1 - len(pre_sbar) - len(post_sbar) statusbarstr = pre_sbar + ("_" * fill_len) + post_sbar sun = "Slunce: " + str(sunrise().strftime("%H.%M")) + "-" + str( sunset().strftime("%H.%M")) moon = "Měsíc: " + str(moon_phase()) zodnow = datetime.datetime.now().strftime("%Y-%m-%d") name_zodiac = "Zvěrokruh: " + str(zodiac(zodnow)) today = datetime.datetime.now().strftime("%d.%m.") day = hlp_day(datetime.datetime.now().strftime("%w")) name_date = datetime.datetime.now().strftime("%m-%d") name_day_name = hlp_nday_qry( "select name from jmeniny where date = '%s'" % name_date) name_day = "Dnes je " + day + " " + today + " a svátek má " + name_day_name[ 0][0] credits = "MMXVIII-MMXX" if k == 0: credits = "MMXVIII-MMXX" keystr = " KLUB [" + str(klub_strana) + "] : " + str( tui_klub_id) # Centering calculations start_x_title = int((width // 2) - (len(title) // 2) - len(title) % 2) start_x_subtitle = int((width // 2) - (len(subtitle) // 2) - len(subtitle) % 2) start_x_keystr = int((width // 2) - (len(keystr) // 2) - len(keystr) % 2) start_x_credits = int((width // 2) - (len(credits) // 2) - len(credits) % 2) start_x_nazev_klubu = int((width // 2) - (len(nazev_klubu) // 2) - len(nazev_klubu) % 2) start_x_sun = int((width // 2) - (len(sun) // 2) - len(sun) % 2) start_x_moon = int((width // 2) - (len(moon) // 2) - len(moon) % 2) start_x_zodiac = int((width // 2) - (len(name_zodiac) // 2) - len(name_zodiac) % 2) start_x_name_day = int((width // 2) - (len(name_day) // 2) - len(name_day) % 2) # Render status bar stdscr.attron(curses.color_pair(3)) stdscr.addstr(height - 1, 0, sutf8(statusbarstr)) stdscr.addstr(height - 1, len(statusbarstr), " " * (width - len(statusbarstr) - 1)) stdscr.attroff(curses.color_pair(3)) # Turning on attributes for title stdscr.attron(curses.color_pair(2)) stdscr.attron(curses.A_BOLD) # Rendering title #stdscr.addstr(start_y, start_x_title, sutf8(title)) # Print rest of text stdscr.addstr( start_y, start_x_title, sutf8(title), ) # Turning off attributes for the rest stdscr.attroff(curses.color_pair(2)) stdscr.attroff(curses.A_BOLD) stdscr.addstr(start_y + 2, start_x_keystr, sutf8(keystr)) stdscr.addstr(start_y + 4, start_x_nazev_klubu, sutf8(nazev_klubu)) stdscr.addstr(start_y + 6, start_x_sun, sutf8(sun)) stdscr.addstr(start_y + 8, start_x_moon, sutf8(moon)) stdscr.addstr(start_y + 10, start_x_name_day, sutf8(name_day)) stdscr.addstr(start_y + 12, start_x_zodiac, sutf8(name_zodiac)) stdscr.move(cursor_y, cursor_x) # Refresh the screen stdscr.refresh() # Wait for next input #k = stdscr.getch() k = ugetch(stdscr)
def __init__(self): self.running = True self.paused = False self.DATA_Y = 1 self.DATA_X = 0 self.DATA_H = 29 self.DATA_W = 32 self.PLAYERS_Y = 1 self.PLAYERS_X = self.DATA_X + self.DATA_W + 2 self.PLAYERS_H = 21 self.PLAYERS_W = 66 self.MAP_Y = 1 self.MAP_X = self.PLAYERS_X + self.PLAYERS_W + 2 self.MAP_H = 0 self.MAP_W = 0 self.PATH_Y = self.PLAYERS_Y + self.PLAYERS_H + 3 self.PATH_X = self.DATA_X + self.DATA_W + 2 self.PATH_H = 5 self.PATH_W = 66 self.LOG_Y = self.DATA_Y + self.DATA_H + 2 self.LOG_X = 0 self.LOG_H = 12 self.LOG_W = self.DATA_W + self.PLAYERS_W + 2 self.HELP_Y = self.LOG_Y + self.LOG_H - 2 self.HELP_X = 1 self.HELP_H = 1 self.HELP_W = self.LOG_W - 2 self.TIME_Y = self.LOG_Y + self.LOG_H + 2 self.TIME_X = 0 self.TIME_H = 0 self.TIME_W = 0 self.MENU_Y = 0 self.MENU_X = 0 self.MENU_H = 24 self.MENU_W = 0 self.SUMMARY_Y = self.LOG_Y + 5 self.SUMMARY_X = self.LOG_X + self.LOG_W + 2 self.SUMMARY_H = 7 self.SUMMARY_W = 20 self.data_win = None self.map_win = None self.path_win = None self.log_win = None self.help_win = None self.players_win = None self.time_win = None self.menu_win = None self.time_win = None self.summary_win = None self.log_entries = [] self.stdscr = curses.initscr() curses.start_color() # Basic color set curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_WHITE) curses.init_pair(2, curses.COLOR_WHITE, curses.COLOR_RED) curses.init_pair(3, curses.COLOR_RED, curses.COLOR_BLACK) curses.init_pair(4, curses.COLOR_YELLOW, curses.COLOR_BLACK) curses.init_pair(5, curses.COLOR_GREEN, curses.COLOR_BLACK) curses.init_pair(6, curses.COLOR_WHITE, curses.COLOR_BLUE) curses.init_pair(7, curses.COLOR_CYAN, curses.COLOR_BLACK) curses.init_pair(8, curses.COLOR_WHITE, curses.COLOR_MAGENTA) curses.init_pair(9, curses.COLOR_WHITE, curses.COLOR_GREEN) curses.init_pair(10, curses.COLOR_WHITE, curses.COLOR_YELLOW) # check for minimal screen size screen_y, screen_x = self.stdscr.getmaxyx() if screen_y < MIN_LINES or screen_x < MIN_COLS: # Try resizing terminal curses.resizeterm(MIN_LINES, MIN_COLS) if not curses.is_term_resized(MIN_LINES, MIN_COLS): self.quit_ui() print "Unable to change your terminal size. Your terminal must be at least", \ MIN_LINES, "lines and", MIN_COLS, "columns and it actually has", \ screen_y, "lines and", screen_x, "columns." quit(1) # Screen is up curses.noecho() curses.cbreak() curses.curs_set(0) self.stdscr.keypad(1)
import RPi.GPIO as GPIO import curses GPIO.setmode(GPIO.BOARD) list_F = [11, 15, 12, 18] list_B = [40, 13, 16, 38] list_L = [11, 15, 16, 38] list_R = [40, 13, 12, 18] GPIO.setup(list_F, GPIO.OUT) GPIO.setup(list_B, GPIO.OUT) GPIO.setup(list_L, GPIO.OUT) GPIO.setup(list_R, GPIO.OUT) stdscr = curses.initscr() # curses initialization curses.noecho() # to turn-off echoing of keybord to screen curses.cbreak() # no waiting key response stdscr.keypad(True) # spciecial values for cursor keys - keypad mode try: while True: c = stdscr.getch() if c == ord('q'): break elif c == ord('s'): GPIO.output(list_F, GPIO.LOW) GPIO.output(list_B, GPIO.LOW) GPIO.output(list_L, GPIO.LOW) GPIO.output(list_R, GPIO.LOW)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import curses import time ekran = curses.initscr() curses.start_color() curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK) curses.init_pair(2, curses.COLOR_CYAN, curses.COLOR_BLACK) curses.init_pair(3, curses.COLOR_RED, curses.COLOR_BLACK) curses.noecho() boyutlar = ekran.getmaxyx() ekran.nodelay(1) bold = 0 reverse = 0 b = [curses.A_NORMAL, curses.A_BOLD] r = [curses.A_NORMAL, curses.A_REVERSE] g = 1 q = -1 x, y = 0, 0 while q != ord("q"): ekran.clear() ekran.addstr(y, x, "hello world!", curses.color_pair(g) | b[bold] | r[reverse]) ekran.move(boyutlar[0] - 1, boyutlar[1] - 1) ekran.refresh() q = ekran.getch() if q in range(49, 52): g = int(chr(q)) elif q == 98: bold = 1 - bold
def intercept(line): """ Intercept requests and/or responses and edit them with before passing them along Usage: intercept <reqid> """ global edit_queue args = shlex.split(line) intercept_requests = False intercept_responses = False req_names = ('req', 'request', 'requests') rsp_names = ('rsp', 'response', 'responses') if any(a in req_names for a in args): intercept_requests = True if any(a in rsp_names for a in args): intercept_responses = True if intercept_requests and intercept_responses: intercept_str = 'Requests and responses' elif intercept_requests: intercept_str = 'Requests' elif intercept_responses: intercept_str = 'Responses' else: intercept_str = 'NOTHING' mangle_macro = MangleInterceptMacro() mangle_macro.intercept_requests = intercept_requests mangle_macro.intercept_responses = intercept_responses add_intercepting_macro('pappy_intercept', mangle_macro) ## Interceptor loop stdscr = curses.initscr() curses.noecho() curses.cbreak() try: editnext = False stdscr.nodelay(True) while True: stdscr.addstr(0, 0, "Currently intercepting: %s" % intercept_str) stdscr.clrtoeol() stdscr.addstr(1, 0, "%d item(s) in queue." % len(edit_queue)) stdscr.clrtoeol() if editnext: stdscr.addstr( 2, 0, "Waiting for next item... Press 'q' to quit or 'b' to quit waiting" ) else: stdscr.addstr( 2, 0, "Press 'n' to edit the next item or 'q' to quit interceptor." ) stdscr.clrtoeol() c = stdscr.getch() if c == ord('q'): break elif c == ord('n'): editnext = True elif c == ord('b'): editnext = False if editnext and edit_queue: editnext = False (to_edit, deferred) = edit_queue.pop(0) editor = 'vi' if 'EDITOR' in os.environ: editor = os.environ['EDITOR'] additional_args = [] if editor == 'vim': # prevent adding additional newline additional_args.append('-b') subprocess.call([editor, to_edit] + additional_args) stdscr.clear() deferred.callback(None) finally: curses.nocbreak() stdscr.keypad(0) curses.echo() curses.endwin() try: remove_intercepting_macro('pappy_intercept') except PappyException: pass # Send remaining requests along while len(edit_queue) > 0: (fname, deferred) = edit_queue.pop(0) deferred.callback(None)
import math import numpy as np import curses from domain.student import * from domain.cousre import * from domain.mark import * dhp = curses.initscr() class dp: def listCourses(): dhp.addstr("lists of Courses:\n") dhp.refresh() for course in Courses: dhp.addstr( "CourseID: [%s] CourseName: [%s] Credits: [%s]\n" % (course.get_cID(), course.get_name(), course.get_credit())) dhp.refresh() def listStudents(): dhp.addstr("lists of student:\n") dhp.refresh() for student in Students: dhp.addstr( "Studentid: [%s] StudentName: [%s] dob: [%s] \n" % (student.get_id(), student.get_name(), student.get_dob())) dhp.refresh() def listMarks(): dhp.addstr("lists of mark:\n") dhp.refresh()
def __init__(self, rcon, config): self.rcon = rcon self.logFile = None self.logThread = None self.cancelCommand = False self.setLogfile(config['logfile']) self.navigation = { 'menu': self.showMenu, 'playermenu': self.showPlayerMenu, 'player': self.showPlayers, 'missionmenu': self.showMissionMenu, 'command': self.showCommandLine } self.mainmenu = [('Refresh Players', self.fetchPlayers), ('Manage Whitelist', self.manageWhitelist), ('Restart Mission...', self.fetchMissions), ('Kick All', self.rcon.kickAll), ('Shutdown Server', self.shutdownServer), ('Restart Server (v1.65)', self.restartServer), ('Exit', None)] self.playermenu = [] self.missionmenu = [] self.backMenu = [('Main Menu', self.getMainMenu)] self.__navigation = self.getMainMenu() self.__prevnav = None # menu cursor position self.position = 0 # is whitelist self.isWhitelist = False # player cursor position self.playerpos = 0 self.players = [] self.posAndSize = { # height, width, ypos, xpos 'menu': [27, 30, 1, 1], 'log': [8, 131, 31, 1], 'cmd': [3, 131, 28, 1], 'cmdTextbox': [1, 120, 29, 3], 'player': [27, 100, 1, 32] } try: self.screen = curses.initscr() if not self.checkMaxSize(): curses.endwin() print('THE TERMINAL WINDOW IS TO SMALL (width/height)') return self.initColors() curses.cbreak() curses.noecho() curses.curs_set(0) self.menuWnd = self.screen.subwin(*self.posAndSize['menu']) self.menuWnd.keypad(1) self.logWnd = self.screen.subwin(*self.posAndSize['log']) self.cmdWnd = self.screen.subwin(*self.posAndSize['cmd']) self.cmdTextbox = self.screen.subwin( *self.posAndSize['cmdTextbox']) self.playerWnd = self.screen.subwin(*self.posAndSize['player']) except: curses.endwin() raise
smsrepeater.border(0) smsrepeater.addstr(1, 4, " ___ __ __ ___", curses.color_pair(1)) smsrepeater.addstr(2, 4, " / __| \/ / __|", curses.color_pair(1)) smsrepeater.addstr(3, 4, " \__ \ |\/| \__ \ ", curses.color_pair(1)) smsrepeater.addstr(4, 4, " |___/_| |_|___/", curses.color_pair(1)) smsrepeater.addstr(5, 4, " ___ ___ ___ ___ _ _____ ___ ___", curses.color_pair(1)) smsrepeater.addstr(6, 4, "| _ \ __| _ \ __| /_\_ _| __| _ \ ", curses.color_pair(1)) smsrepeater.addstr(7, 4, "| / _|| _/ _| / _ \| | | _|| /", curses.color_pair(1)) smsrepeater.addstr(8, 4, "|_|_\___|_| |___/_/ \_\_| |___|_|_\ ", curses.color_pair(1)) smsrepeater.addstr(10, 4, " SMS Repeater: github.com/reaper4exg ", curses.color_pair(1)) #smsrepeater.endwin() def LogicLoop(): mainmenu() try: smsrepeater = curses.initscr() hedr() LogicLoop() finally: print(":)") curses.endwin() sys.exit()
def init_curses(self): self.screen = curses.initscr() self.screen.keypad(True) curses.noecho() curses.mousemask(True)
def main(win): global stdscr stdscr = win curses.initscr() curses.nl() curses.noecho() #Instantiate the devices and objects we need dio = Dio() adc0 = Adc(0) dac0 = Dac(0) adc1 = Adc(1) dac1 = Dac(1) adc0.setOneShotMode() adc1.setOneShotMode() stdscr.clear stdscr.move(1,20) stdscr.addstr("YIG DRIVER LOOPBACK") stdscr.move(2,1) stdscr.addstr("volts: ") stdscr.move(4,1) stdscr.addstr("ANALOG_IN_1: ") stdscr.move(5,1) stdscr.addstr("ANALOG_IN_2: ") stdscr.move(6,1) stdscr.addstr("ANALOG_IN_5: ") stdscr.move(7,1) stdscr.addstr("ANALOG_IN_6: ") stdscr.move(9,1) stdscr.addstr("DIO OUT") stdscr.move(9,12) stdscr.addstr("DIO IN") # stdscr.move(10,1) # stdscr.addstr("0: ") # stdscr.move(11,1) # stdscr.addstr("1: ") # stdscr.move(12,1) # stdscr.addstr("2: ") # stdscr.move(13,1) # stdscr.addstr("4: ") stdscr.move(19,1) stdscr.addstr("Unix Time mod 7:") stdscr.move(20,1) stdscr.addstr("unix time: ") stdscr.refresh() bit_weight = 2.048 / 65535 out_volts = 0.0 in_volts = 0.0 cal_1 = 10.0 cal_2 = 10.0 cal_3 = 10.0 cal_4 = 10.0 err_1 = 0.0 err_2 = 0.0 err_3 = 0.0 err_4 = 0.0 digits = np.zeros(10,dtype=int) unix_time = 0 dio_bits = 0 def check_db(): dac0.write(2,32767) # U3-7 V_OUTC Analog_Out_3 dac1.write(2,32767) # U6-7 V_OUTC Analog_Out_7 i = 0 while True: sleep(1.0) unix_time = int(time.time()) u_t = unix_time for j in range(10): digit = u_t % 10 digits[9-j] = digit u_t /= 10 for j in range(10): stdscr.move(20,15) stdscr.clrtoeol() stdscr.addstr(str(unix_time)) # i = i + 255 i = digits[j] / bit_weight / 5.0 out_volts = bit_weight * i * 5.0 stdscr.move(2,15) stdscr.clrtoeol() stdscr.addstr(str(out_volts)) dac0.write(0,i) # U3-1 V_OUTA Analog_Out_1 YIG_1_tune dac1.write(0,i) # U6-1 V_OUTA Analog_Out_5 YIG_2_tune dac0.write(1,i) # U3-2 V_OUTB Analog_Out_2 YIG_1_atten dac0.write(3,i) # U6-2 V_OUTB Analog_Out_6 YIG_2_atten Analog_In_1 = adc0.read(0) in_volts = bit_weight * Analog_In_1 * cal_1 err_1 = out_volts - in_volts stdscr.move(4,15) stdscr.clrtoeol() stdscr.addstr(str(in_volts)) stdscr.move(4,32) stdscr.addstr("volts") stdscr.move(4,38) stdscr.addstr(str(err_1)) stdscr.move(4,56) stdscr.addstr("volts") Analog_In_2 = adc0.read(1) in_volts = bit_weight * Analog_In_2 * cal_2 err_2 = out_volts - in_volts stdscr.move(5,15) stdscr.clrtoeol() stdscr.addstr(str(in_volts)) stdscr.move(5,32) stdscr.addstr("volts") stdscr.move(5,38) stdscr.addstr(str(err_2)) stdscr.move(5,56) stdscr.addstr("volts") Analog_In_5 = adc1.read(0) in_volts = bit_weight * Analog_In_5 * cal_3 err_3 = out_volts - in_volts stdscr.move(6,15) stdscr.clrtoeol() stdscr.addstr(str(in_volts)) stdscr.move(6,32) stdscr.addstr("volts") stdscr.move(6,38) stdscr.addstr(str(err_3)) stdscr.move(6,56) stdscr.addstr("volts") Analog_In_6 = adc1.read(1) in_volts = bit_weight * Analog_In_6 * cal_4 err_4 = out_volts - in_volts stdscr.move(7,15) stdscr.clrtoeol() stdscr.addstr(str(in_volts)) stdscr.move(7,32) stdscr.addstr("volts") stdscr.move(7,38) stdscr.addstr(str(err_4)) stdscr.move(7,56) stdscr.addstr("volts") dio_bits = unix_time % 7 stdscr.move(10,1) stdscr.clrtoeol() stdscr.addstr(str(dio_bits)) bit = bin(dio_bits).replace("0b","") length = len(bit) stdscr.move(19,22) stdscr.clrtoeol() stdscr.addstr(str(bit)) pos = bit[0] if pos == '0': dio.setBit(2,0,0) else: dio.setBit(2,1,0) if length > 1: pos = bit[1] if pos == '0': dio.setBit(1,0,0) else: dio.setBit(1,1,0) else: dio.setBit(1,0,0) if length > 2: pos = bit[2] if pos == '0': dio.setBit(0,0,0) else: dio.setBit(0,1,0) else: dio.setBit(0,0,0) readback = dio.read(1) stdscr.move(10,15) stdscr.clrtoeol() stdscr.addstr(str(readback)) stdscr.refresh() # zero the dacs dac0.write(0,0) # U3-1 V_OUTA Analog_Out_1 YIG_1_tune dac1.write(0,0) # U6-1 V_OUTA Analog_Out_5 YIG_2_tune dac0.write(1,0) # U3-2 V_OUTB Analog_Out_2 YIG_1_atten dac0.write(3,0) # U6-2 V_OUTB Analog_Out_6 YIG_2_atten check_db() curses.nocbreak(); stdscr.keypad(0); curses.echo()
from random import * import time, sys import curses as h w = h.initscr() h.noecho() # P, Q, m, s, e, p, a, q = 20, 10, 5, 300, { 0: "· ", 1: "██" }, [ [[1, 1]] * 2, [[0, 1, 0], [1] * 3, [0] * 3], [ [ 1 # , 0, 0 ], [1] * 3, [0] * 3 ], [[0, 0, 1], [1] * 3, [0] * 3], [[1, 1, 0], [0, 1, 1], [0] * 3], [ [0, 1, 1], [ 1, 1, 0 # ], [0] * 3
HEIGHT = 20; WIDTH = 14; import curses; import random; import os; import datetime; blockPos = [3,WIDTH/2,0,random.randrange(0,7,1)]; next = random.randrange(0,7,1); nextB = ['---','-|_','_|-','__|','|__','[] ','_|_']; initime = datetime.datetime.now(); scr = 0; curses.initscr(); curses.curs_set(0); win = curses.newwin(HEIGHT,WIDTH,0,0); win.keypad(1); win.nodelay(1); blocks = [ [[0,-2],[0,-1],[0,0],[0,1]], [[-1,-1],[-1,0],[0,0],[0,1]], [[0,-1],[0,0],[-1,0],[-1,1]], [[0,-1],[0,0],[0,1],[-1,1]], [[-1,-1],[0,-1],[0,0],[0,1]], [[0,-1],[0,0],[1,-1],[1,0]], [[0,-1],[0,0],[0,1],[-1,0]] ]; curses.start_color(); curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_GREEN); curses.init_pair(2, curses.COLOR_YELLOW, curses.COLOR_YELLOW); curses.init_pair(3, curses.COLOR_WHITE, curses.COLOR_BLACK); curses.init_pair(4, curses.COLOR_RED, curses.COLOR_RED); curses.init_pair(5, curses.COLOR_BLUE, curses.COLOR_BLUE); curses.init_pair(6, curses.COLOR_WHITE, curses.COLOR_BLUE); win.addch(0,0,' '); win.addch(0,1,'.',curses.color_pair(1)); win.addch(0,2,',',curses.color_pair(2)); win.addch(0,3,' ',curses.color_pair(3)); win.addch(0,4,'\'',curses.color_pair(4)); drawType = [win.inch(0,0),win.inch(0,1),win.inch(0,2),win.inch(0,3),win.inch(0,4)] def hitCheck(key,d): for i in range(4): y = blockPos[0] + turnBlock(blockPos, blocks[blockPos[3]][i][0], blocks[blockPos[3]][i][1])[0]; x = blockPos[1] + turnBlock(blockPos, blocks[blockPos[3]][i][0], blocks[blockPos[3]][i][1])[1] if y >= HEIGHT - 1 : blockPos[0] -= d; return 1 elif x >= WIDTH - 1 or x <= 0: moveBlock(blockPos,key,-1,initime); curses.beep(); elif win.inch(y,x) == drawType[2]: if key in [curses.KEY_LEFT,curses.KEY_RIGHT,curses.KEY_DOWN,curses.KEY_UP]: moveBlock(blockPos,key,-1,initime); return 1 if key == curses.KEY_DOWN else curses.beep(); else: blockPos[0] -= 1; return 1 def drawBlock(blockPos,type): mark = '.' if type == 1 else ',' if type == 2 else ' ' for i in range(4): win.addch(blockPos[0] + turnBlock(blockPos, blocks[blockPos[3]][i][0], blocks[blockPos[3]][i][1])[0], blockPos[1] + turnBlock(blockPos, blocks[blockPos[3]][i][0], blocks[blockPos[3]][i][1])[1], mark, curses.color_pair(type)) win.addch(0,3,' ',curses.color_pair(3)); for i in range(4): for j in range(1,HEIGHT - blockPos[0]) : if win.inch(blockPos[0] + turnBlock(blockPos, blocks[blockPos[3]][i][0], blocks[blockPos[3]][i][1])[0] + j, blockPos[1] + turnBlock(blockPos, blocks[blockPos[3]][i][0], blocks[blockPos[3]][i][1])[1]) == drawType[0] or win.inch(blockPos[0] + turnBlock(blockPos, blocks[blockPos[3]][i][0], blocks[blockPos[3]][i][1])[0] + j, blockPos[1] + turnBlock(blockPos, blocks[blockPos[3]][i][0], blocks[blockPos[3]][i][1])[1]) == drawType[3] : win.addch('\'', curses.color_pair(4)) else : break def moveBlock(blockPos,key,d,init): if d and (60 + now.second - init.second) % 60 >= 1 : blockPos[0] += d; global initime; initime = datetime.datetime.now(); blockPos[1] = blockPos[1] - d if key == curses.KEY_LEFT else blockPos[1] + d if key == curses.KEY_RIGHT else blockPos[1]; blockPos[0] = blockPos[0] + d if key == curses.KEY_DOWN else blockPos[0]; if key == curses.KEY_UP : blockPos[2] = (blockPos[2] + 1) % 4 if not d == -1 else (blockPos[2] + 3) % 4 def turnBlock(blockPos,y,x): sin = [0,1,0,-1]; cos = [1,0,-1,0]; return [y,x] if blockPos[3] == 5 else [y * cos[blockPos[2]] - x * sin[blockPos[2]], y * sin[blockPos[2]] + x * cos[blockPos[2]]] def lineClr(): for y in range(2,HEIGHT-1): if all(win.inch(y,x) == drawType[2] for x in range(1,WIDTH-1)): win.deleteln(); win.move(2,1); win.insertln(); curses.beep(); curses.flash(); global scr; scr += 1 def sweep(): for y in range(2,HEIGHT-1): for x in range(1,WIDTH-1): if win.inch(y,x) == drawType[4]: win.addch(y,x,' ',curses.color_pair(3))
""" Filename: snake_main.py Author: Kyle Cookerly Description: Console-based Snake clone, written in Python 3.5.1 using the curses module. """ import curses # For terminal control from game import Game from game_state_screens import draw_start_window, draw_game_over_window, draw_option_select_window curses.initscr() # Starts screen curses.noecho() # Hides the keyboard input from the terminal curses.curs_set(0) def main(): draw_start_window() game_mode = draw_option_select_window() # Draws the option screen and assigns the value received to game_mode snake_game = Game(game_mode) while not snake_game.is_game_over(): snake_game.run_game() snake_game.end_window() draw_game_over_window(snake_game.get_game_score()) if __name__ == "__main__":