def countdown(self, scr, inspection = 15.0): scr.clear() maxqy, maxqx = scr.getmaxyx() ret = 0 start = time() c = -1 while c < 0 or c == curses.KEY_RESIZE: scr.clear() delta = inspection + start - time() if delta > 0: s = '%.2f' % delta elif delta > -2: s = '+2' ret = 2 else: s = 'DNF' ret = 'DNF' scr.addstr(maxqy//2 - 1, (maxqx - len(s))//2, s) scr.refresh() c = scr.getch() curses.napms(10) curses.beep() return ret
def main(window, pattern): curses.nl() curses.noecho() window.timeout(0) current_direction, cur_point = reset_window(window) index = 0 while True: if index == len(pattern): index = 0 direction = get_new_direction(current_direction, pattern[index]) try: cur_point = draw_line(window, cur_point, direction, current_direction) current_direction = direction index += 1 except OutOfBoundsError: current_direction, cur_point = reset_window(window) ch = window.getch() if ch == ord('q') or ch == ord('Q'): return elif ch == ord('s'): # for debugging allow us to step through program window.nodelay(0) elif ch == ord(' '): window.nodelay(1) curses.napms(100)
def check_input(self): if self.inp == 65: s = "up" elif self.inp == 66: s = "down" elif self.inp == 68: s = "left" elif self.inp == 67: s = "right" else: s = "?" if s != "?": merged = [[] for i in xrange(4)] tempscore, factor = 0, 0 if self.spielfeld.lines_movable(s, merged): while self.spielfeld.lines_movable(s, merged): tempscore, factor = self.spielfeld.single_step(s, merged, tempscore, factor) self.myscreen.clear() self.draw_surroundings() self.myscreen.refresh() curses.napms(50) self.spielfeld.add_numbers() self.spielfeld.score += factor * tempscore if self.spielfeld.gameover(merged): self.gameover = True elif self.spielfeld.win(): self.win = True
def main(): signal.signal(signal.SIGINT, signal_handler) locale.setlocale(locale.LC_ALL, "") # Use system's default encoding stdscr = curses.initscr() # Initialize curses.cbreak() # Enter cbreak mode curses.noecho() # Don't echo any characters curses.curs_set(0) # Make cursor invisible stdscr.nodelay(1) # Make getch() non-blocking stdscr.keypad(1) # Interpret escape sequences snk = Snake(stdscr.getmaxyx()) # Initialize our Snake!! ch = None while ch != curses.ascii.ESC: stdscr.clear() direction = None if ch == curses.KEY_UP: direction = Direction.north elif ch == curses.KEY_DOWN: direction = Direction.south elif ch == curses.KEY_LEFT: direction = Direction.west elif ch == curses.KEY_RIGHT: direction = Direction.east snk.move(stdscr, direction) snk.draw(stdscr) stdscr.refresh() curses.napms(200) ch = stdscr.getch() curses.flushinp() curses.endwin()
def manage_keys(self): """process key presses""" self.frame.win.nodelay(1) while 1: ch = self.frame.win.getch() if ch == -1: # no key pressed curses.napms(1) curses.doupdate() continue #print 'key: \'%s\' <=> %c <=> 0x%X <=> %d' % \ #(curses.keyname(ch), ch & 255, ch, ch) ret = keys.do(self.act_tab, ch) if ret == SELECT_UPDATE: if self.act_tab.fix_limits() ==1: self.app.display() else: self.display_cursorbar(1) #erase self.display_cursorbar(0) #draw self.app.statusbar.set_strings(\ self.app.act_pane.act_tab.build_status_line()) self.app.statusbar.refresh() continue if ret != None: return ret self.app.display()
def main(): global scrn curses_set() display_screen() set_calibrationmode("ON") get_calib_initial() reset_calib() while True: get_calib_coordinates() display_values() swap_c2l() c = scrn.getch() if c==-1: curses.napms(350) elif c==113 or c==81: break elif c==114 or c==82: reset_calib() elif c==115 or c==83: set_values() break set_calibrationmode("OFF") curses_reset()
def __init__(self, parent, log): ''' ''' wx.StatusBar.__init__( self, parent, id=-1) self.log = log if statusBarTestDrive: # This status bar has three fields self.SetFieldsCount(3) # Sets the three fields to be relative widths to each other. self.SetStatusWidths([-2, -1, -2]) self.sizeChanged = False ## self.Bind(wx.EVT_SIZE, self.OnSize) ## self.Bind(wx.EVT_IDLE, self.OnIdle) # Field 0 ... just text self.SetStatusText("1st Customized Field", 0) ## self.ts_Handle.refresh() self.SetStatusText("2nd", 1) ## self.ts_Handle.refresh() # TBD - Remove Show ## self.ts_Handle.refresh() ## curses.napms(wx.napTimeMilliseconds) if True: self.SetStatusText("3rd Customized Field", 2) ## self.ts_Handle.refresh() else: import curses t = time.localtime(time.time()) st = time.strftime("%d-%b-%Y %I:%M:%S", t) self.SetStatusText(st, 2) self.ts_Handle.refresh() curses.napms(wx.napTimeMilliseconds) else: # This will fall into field 1 (the second field) self.cb = wx.CheckBox(self, 1001, "toggle clock") self.Bind(wx.EVT_CHECKBOX, self.OnToggleClock, self.cb) self.cb.SetValue(True) # set the initial position of the checkbox self.Reposition() # We're going to use a timer to drive a 'clock' in the last # field. self.timer = wx.PyTimer(self.Notify) self.timer.Start(1000) self.Notify()
def changeScreen(new_key_str, change_delay=0, infobox_key=None,change_msg=""): """ changes current view to new screen """ global curse_container global current_screen global screen_key global previous_key if current_screen != None: # REDIRECT DELAY if change_delay == 0: current_screen.hideScreen() else: infobox = curse_container.getTextboxByName(infobox_key) infobox.refresh(change_msg) curses.napms(3000) current_screen.hideScreen() if new_key_str == "_previous": if previous_key != None: new_key_str = previous_key current_screen = curse_container.screens[new_key_str] if new_key_str == "title_screen": logout() current_screen.showScreen() if previous_key != None: previous_key = screen_key else: previous_key = "none" screen_key = new_key_str
def main(win): global stdscr stdscr = win if curses.has_colors(): bg = curses.COLOR_BLACK curses.init_pair(1, curses.COLOR_BLUE, bg) curses.init_pair(2, curses.COLOR_CYAN, bg) curses.nl() # new line curses.noecho() stdscr.timeout(0) x = 0 y = 0 while True: draw_map() stdscr.addch(y, x, ord("*")) y, x = auto_run(y, x) ch = stdscr.getch() if ch == ord("q") or ch == ord("Q"): return stdscr.erase() # erase and refresh should have a proper interval curses.napms(100) stdscr.refresh()
def main(): """ Main entry point for gunicorn_console. """ # Set up curses. stdscr = curses.initscr() curses.start_color() curses.init_pair(1, foreground_colour, background_colour) curses.noecho() stdscr.keypad(True) stdscr.nodelay(True) try: curses.curs_set(False) except: pass try: # Run main event loop until quit. while True: try: update_gunicorns() handle_keypress(stdscr) display_output(stdscr) curses.napms(int(screen_delay * 1000)) except KeyboardInterrupt: break finally: # Tear down curses. curses.nocbreak() stdscr.keypad(False) curses.echo() curses.endwin()
def runBoot(scr, hardMode): """ Start the boot portion of the terminal hardMode - boolean indicating whether the user has to enter the ENTRY constants, or if they are entered automatically """ curses.use_default_colors() scr.erase() scr.move(0, 0) curses.noecho() scr.scrollok(True) slowWrite(scr, MESSAGE_1 + '\n\n') if hardMode: # use must enter the correct text to proceed entry = '' while entry.upper() != ENTRY_1.upper(): slowWrite(scr, '>') entry = upperInput(scr) else: # input is entered for them slowWrite(scr, '>') curses.napms(INPUT_PAUSE) slowWrite(scr, ENTRY_1 + '\n', TYPE_DELAY) slowWrite(scr, '\n' + MESSAGE_2 + '\n\n') if hardMode: entry = '' while entry.upper() != ENTRY_2.upper(): slowWrite(scr, '>') entry = upperInput(scr) while entry.upper() != ENTRY_3.upper(): slowWrite(scr, '>') entry = upperInput(scr) else: slowWrite(scr, '>') curses.napms(INPUT_PAUSE) slowWrite(scr, ENTRY_2 + '\n', TYPE_DELAY) slowWrite(scr, '>') curses.napms(INPUT_PAUSE) slowWrite(scr, ENTRY_3 + '\n', TYPE_DELAY) slowWrite(scr, '\n' + MESSAGE_3 + '\n\n') if hardMode: entry = '' while entry.upper() != ENTRY_4.upper(): slowWrite(scr, '>') entry = upperInput(scr) else: slowWrite(scr, '>') curses.napms(INPUT_PAUSE) slowWrite(scr, ENTRY_4 + '\n', TYPE_DELAY) curses.napms(INPUT_PAUSE) return True
def main(self): self.F = npyscreen.Form(name = "Welcome to Npyscreen") self.t = self.F.add(npyscreen.TitleText, name = "Text:") while 1: self.update_values() curses.flash() curses.napms(100)
def run(self): curses.cbreak() curses.noecho() output.lastline() output.overwriteline() self.prompt() output.scr.refresh() last = None for item in self.data: if item[0] != None: if not self.inahurry: if last != None: curses.napms(600 + len(last)*30) else: curses.napms(1000) self.receive(item[0], item[1]) output.scr.refresh() last = item[1] else: self.send(item[1]) output.openline() self.prompt() output.scr.refresh() last = None output.removelastline()
def playerProjectile(press): global projectileWidth,projectileHeight,projectileExist, projectileMisses, enemy1Health,powerUpPickedUp,playerHeight,playerWidth if powerUpPickedUp == True and press == 112: if pygameAvailable == True: pygame.mixer.Sound.play(explosionSound) powerUpPickedUp = False for x in range (1,37): for y in range (playerHeight-1,1,-1): window.addstr(y,x, "█", curses.color_pair(2));window.refresh() curses.napms(3) for x in range (1,37): for y in range (playerHeight-1,1,-1): window.addstr(y,x, " ");window.refresh() enemy1Health -= 1 press = 0 #so that it doesn't shoot fater activating the power up if projectileExist == False: if press == 32: if pygameAvailable == True: pygame.mixer.Sound.play(playerShootSound) projectileHeight = playerHeight - 1 projectileWidth = playerWidth projectileExist = True window.addstr(projectileHeight,projectileWidth, "|", curses.color_pair(2)) if press == 27: enemy1Health = 0 if projectileExist == True: if projectileHeight == 2: projectileExist = False projectileMisses += 1 window.addstr(projectileHeight,projectileWidth, "|", curses.color_pair(2)) window.addstr(projectileHeight,projectileWidth, " ") else: projectileHeight -=1 window.addstr(projectileHeight,projectileWidth, "|", curses.color_pair(2)) window.addstr(projectileHeight+1,projectileWidth," ")
def testloop(sa): import screen_area SA = screen_area.ScreenArea() w = TitleText(SA, use_two_lines=True, rely = 23, value="testing") w.value = 'this is a new test' w.edit() curses.napms(2500)
def main(): global timeValue defaultValues() #curses.raw() genericMusicPlaying = False window.bkgd(' ', curses.color_pair(1)) if borderBuilt == False: buildBorder() #creates the outer border of the window if pygameAvailable == False: noPyGame() titleScreen() #runs the title screen sequence countdownTitleScreen() timeValue = time.time() window.addstr(playerHeight,playerWidth, "P", curses.color_pair(3)) #creates the initial graphic for the player while 1: getch = window.getch() movePlayer(getch) playerProjectile(getch) hitDetection() enemy1() powerUp() topDisplay() enemy1Projectile() curses.napms(50) if pygameAvailable == True and genericMusicPlaying == False: pygame.mixer.Sound.play(genericmusicSound, loops=-1) genericMusicPlaying = True
def update(self, servers_list): """Update the servers' list screen. Wait for __refresh_time sec / catch key every 100 ms. servers_list: Dict of dict with servers stats """ # Flush display self.flush(servers_list) # Wait exitkey = False countdown = Timer(self.__refresh_time) while not countdown.finished() and not exitkey: # Getkey pressedkey = self.__catch_key(servers_list) # Is it an exit or select server key ? exitkey = ( pressedkey == ord('\x1b') or pressedkey == ord('q') or pressedkey == 10) if not exitkey and pressedkey > -1: # Redraw display self.flush(servers_list) # Wait 100ms... curses.napms(100) return self.get_active()
def main(stdscr): stdscr.addstr(0,0, "Welcome!\nSelect what to do:") stdscr.addch(2,3, 'L', curses.A_BOLD) stdscr.addstr(2,4, "ist current scouts") stdscr.addch(3,3, 'E') stdscr.addch(3,4, 'x', curses.A_BOLD) stdscr.addstr(3,5, "it") stdscr.hline(5,0, '-', 40) while True: stdscr.addstr(6,0, "Select choice: ", curses.A_STANDOUT) stdscr.refresh() choice = stdscr.getch() if choice in (ord('l'),ord('L')): year = datetime.date.today().year - 11 cur.execute("SELECT * FROM BasicInfo WHERE birthDate > ?-00-00", (str(year),)) for row in cur: stdscr.clear() buf = row[1].ljust(10) + row[0] + "\n" stdscr.addstr(buf.encode('utf8')) stdscr.refresh() stdscr.getch() elif choice in (ord('x'),ord('X')): return 0 else: stdscr.addstr(6,0, "Invalid choice", curses.A_STANDOUT) stdscr.refresh() curses.napms(500)
def testme(sa): import screen_area SA = screen_area.ScreenArea() w = TitleSlider(SA, rely = 10, relx=5) w.edit() w.display() curses.napms(1500)
def main( scr ): prevul_total, prevul_mtc, prevul_star = None, None, None prevdl_total, prevdl_mtc, prevdl_star = [], [], [] 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 ) speedWnd = curses.newpad( 10, 110 ) while True: dl_total = parseTable( getoutput( 'iptables -xnvL count_in | tail -n+3' ).split( '\n' ), False ) dl_mtc = parseTable( getoutput( 'iptables -xnvL count_mtc_in | tail -n+3' ).split( '\n' ), False ) #dl_star = parseTable( getoutput( 'iptables -xnvL count_star_in | tail -n+3' ).split( '\n' ), False ) ul_total = parseTable( getoutput( 'iptables -xnvL count_out | tail -n+3' ).split( '\n' ) ) ul_mtc = parseTable( getoutput( 'iptables -xnvL count_mtc_out | tail -n+3' ).split( '\n' ) ) #ul_star = parseTable( getoutput( 'iptables -xnvL count_star_out | tail -n+3' ).split( '\n' ) ) printTable( speedWnd, ( 'D/total', dl_total, prevdl_total, 4000 ), ( 'U/total', ul_total, prevul_total, 3100 ), ( 'D/mtc', dl_mtc, prevdl_mtc, 2000 ), ( 'U/mtc', ul_mtc, prevul_mtc, 100 ), # ( 'D/star', dl_star, prevdl_star, 3000 ), # ( 'U/star', ul_star, prevul_star, 3000 ) ) prevdl_total, prevul_total = dl_total, ul_total prevdl_mtc, prevul_mtc = dl_mtc, ul_mtc # prevdl_star, prevul_star = dl_star, ul_star scr.erase() scr.refresh() ( sh, sw ) = scr.getmaxyx() ( h, w ) = speedWnd.getmaxyx() try: speedWnd.refresh( 0, 0, 0, 0, min( h, sh ) - 1, min( w, sw ) - 1 ) except curses.error: pass for i in xrange( 10 ): curses.napms( 100 )
def game_start(stdscr): """ Houses the game-loop. draws sleeps , calls collide to check """ global birdy curses.flash()#flash the screen curses.curs_set(0)#set the cursor invisible stdscr.nodelay(1) while True: stdscr.erase() draw_border(stdscr,score) draw_bird(stdscr) draw_pipes(stdscr) #if collide()==True: # game_over(stdscr,score) # pass up=stdscr.getch() if up==ord(' '): if birdy<=10: birdy=10 pass else: birdy-=1 pass pass else: y,x=stdscr.getmaxyx() if birdy>=y-10: birdy=y-10 pass else: birdy+=1 pass curses.flushinp() curses.napms(20)
def main(): global rain rain = [] g = X() thunder() tears = [] ; starts = [] for a in range(0,rate): tears.append\ (drop(random.randint(0, curses.COLS),'')); starts.append(random.randint(5,fade)) while True: g.step() for I in xrange(len(tears)): if starts[I] > 0: lastA, lastS = tears[I], starts[I] tears.pop(I) starts.pop(I) tears = [lastA]+tears starts = [lastS-1]+starts else: tears[I].step(g) if not tears[I].alive: tears[I].dead() tears[I]=drop(random.randint(0, curses.COLS),thunder()) starts[I] = random.randint(5,fade) g.draw() g.w.refresh() curses.napms(delay)
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 main(args): index = args.source impulse.setSourceIndex( index ) peak_heights = [ 0 for i in range( 32 ) ] if curses: try: stdscr = curses.initscr() curses.noecho() curses.cbreak() curses.curs_set(0) stdscr.keypad(1) stdscr.nodelay(1) # make getch non-blocking draw_mode = ('horizontal','left','top') # default mode for draw_curses while True: calc_heights(peak_heights,args.size) draw_mode = get_mode_curses(stdscr,draw_mode) draw_curses(stdscr,peak_heights,draw_mode) curses.napms(int(args.sleep*1000)) finally: curses.nocbreak(); stdscr.keypad(0); curses.echo() curses.curs_set(1) curses.endwin() else: while True: calc_heights(peak_heights,args.size) draw_cli(peak_heights) sleep(args.sleep)
def focus(self): self.__active = True self.refresh() # hide cursor if shown try: curses.curs_set(0) # hide cursor except: pass while 1: # enable interpreted escape character sequences self.window.keypad(1) # get key press (non-blocking) key = self.window.getch() # return false on tab, true on enter if key == 9: pressed = False break elif key == 10: pressed = True break curses.napms(50) self.__active = False self.refresh() return pressed
def confirm(scr): msg_str="Setting updated" scr.clear() scr.border() scr.addstr(2, int((COLS - len(msg_str)) / 2), msg_str) scr.refresh() curses.napms(2000)
def command(self, scr, command): if command == "reset": self.reset() elif command == "solve": q = self.two_phase_solution() scr.addstr(0, 0, str(q[0])) scr.addstr(1, 0, "Solve time: %.2f seconds" % q[1]) scr.addstr(2, 0, "Apply this solution? (y/n): ") if chr(scr.getch()) == "y": scr.nodelay(1) for t in TurnSequence(q[0]): self.apply_turn(t) self.printcube(scr) curses.napms(100) scr.getch() scr.nodelay(0) elif command == "sexy": self.apply("R U R' U'") elif command == "scramble": scr.addstr(0, 0, str(self.scramble())) elif command == "solved?": scr.addstr(0, 0, str(self.is_solved())) elif command == "exit": self.exit() elif command == "help": self.help(scr) else: try: self.apply(TurnSequence(command)) except: scr.addstr(0, 0, "Invalid move: %s" % command)
def main(win): global stdscr stdscr = win if curses.has_colors(): bg = curses.COLOR_BLACK curses.init_pair(1, curses.COLOR_BLUE, bg) curses.init_pair(2, curses.COLOR_CYAN, bg) curses.nl() # new line curses.noecho() stdscr.timeout(0) x = 0 y = 0 while True: # We should get the border of screen max_y, max_x = stdscr.getmaxyx() draw_map() stdscr.addch(y, x, ord('*')) ch = stdscr.getch() if ch == ord('q') or ch == ord('Q'): return # I think we should do collision check when people # press the key elif ch == curses.KEY_DOWN: y += 1 if (y > max_y - 1): y = max_y - 1 elif collision_check(y, x): y -= 1 stdscr.erase() elif ch == curses.KEY_UP: y -= 1 if (y < 0): y = 0 elif collision_check(y, x): y += 1 stdscr.erase() elif ch == curses.KEY_RIGHT: x += 1 if (x > max_x - 1): x = max_x - 1 elif collision_check(y, x): x -= 1 stdscr.erase() elif ch == curses.KEY_LEFT: x -= 1 if (x < 0): x = 0 elif collision_check(y, x): x += 1 stdscr.erase() stdscr.refresh() curses.napms(10)
def slowWrite(window, text, pause = LETTER_PAUSE): """ wrapper for curses.addstr() which writes the text slowely """ for i in xrange(len(text)): window.addstr(text[i]) window.refresh() curses.napms(pause)
def look_out(msecs): curses.napms(msecs) if stdscr.getch() != -1: curses.beep() sys.exit(0)
def insstr(self, *args): (y, x, s, attr, atcursor) = self._getaddinsparms(args, "insstr") orig_y = y orig_x = x if (y >= len(self.buf)): # Inserting to the end is the same as adding to the end self.addstr(y, x, s, attr) return # Get whatever follows after the insert b = self.buf[y] a = self.attr[y] afterb = b[x:] aftera = a[x:] self.clrtoeol(y, x) # Make room for the string and call addstr nlcount = s.count("\n") for i in range(0, nlcount): self.insertln(y + 1) pass self.addstr(y, x, s, attr) # Now insert the cut string, making sure to get the attributes right if (len(a) > 0): y += nlcount x = len(self.buf[y]) new_x = x ca = aftera[0] beg = 0 for i in range(1, len(aftera)): if (aftera[i] != ca): self._addstr(y, x + beg, afterb[beg:i], ca) ca = aftera[i] beg = i pass pass self._addstr(y, x + beg, afterb[beg:], ca) pass self.refresh() curses.napms(1000) if (atcursor): self.cury = y self.curx = x pass elif (self.cury > orig_y): self.cury += nlcount elif (self.cury == orig_y and self.curx >= orig_x): self.cury += nlcount self.curx = self.curx - orig_x + new_x pass return
def input(self, screen): screen.addstr("Enter name: ") self.__name = screen.getstr() screen.addstr("Enter ID: ") self.__ID = screen.getstr() screen.addstr("Enter DoB: ") self.__DoB = screen.getstr() screen.refresh() curses.napms(3000) screen.clear() screen.refresh()
def main(): print("Preparing to initialize screen...") screen = curses.initscr() print("Screen initialized.") screen.refresh() curses.napms(2000) curses.endwin() print("Window ended.")
def gameplay(self): self.change_state("betting") self._betting() self.change_state("dealing") self._dealing() self.change_state("turn") self._turn() self.change_state("scoring") self._scoring() curses.napms(1000) self.check_losers()
def _run_game(self): while True: for y in range(self.gol.height): for x in range(self.gol.width): self._display_glyph(x, y) if not self.gol.at_equilibrium: self.gol.step() self._display_status() self._screen.refresh() curses.napms(self.update_interval)
def __display_standing_start_annoucement(self, resize_x, resize_y): if self.standing_start_announcement: #display the map self.__window.refresh() curses.napms(200) #display the announcement self.__window.addstr(self.__level.objects[6].y+4+resize_y, self.__level.objects[6].x+1+resize_x, READY, curses.color_pair(2)) self.__window.refresh() curses.napms(200)
def animation_off(screen, text, line, off, flicker): column = 2 text_animation = list(text) for i in text_animation: column += 1 screen.addstr(line, column, i, curses.color_pair(2)) screen.refresh() curses.napms(off) screen.addstr(line, 3, str(text), curses.color_pair(2))
def main(screen): writer = Writer(screen) stat = Status(screen) key = Key_hander(screen, stat) #Keep restarting however many times the screen resizes while True: canvas = Canvas(screen) #Loop to draw the green rain while canvas.size_changed == False: #Catch keypress if key.get(): continue #Spawn new nodes for col in canvas.columns: if col.timer == 0: col.spawn_node(canvas) col.timer -= 1 for node in col.nodes: writer.draw(node) #Move node down node.y_coord += 1 #Mark old nodes for deletion if node.y_coord >= canvas.row_count: if node.white: #Stop white nodes from staying 'stuck' on last row. #Creates a special green node with a last_char #attribute to overwrite last white node. node.white = False node.y_coord -= 1 else: node.expired = True #Rewrite nodes list without expired nodes col.nodes = [node for node in col.nodes if not node.expired] #End of loop, refresh screen if stat.countdown > 0: if stat.countdown == 1: stat.clear() else: stat.refresh() stat.countdown -= 1 screen.refresh() #Check for screen resize if screen.getmaxyx() != (canvas.row_count, canvas.col_count): canvas.size_changed = True #Add delay before next loop curses.napms(key.delay)
def cleartest(screen): import screen_area SA = screen_area.ScreenArea() w = TitleText(SA, name="Test", rely=1, relx=3) w.value = "This is some text! height: %s, width %s" % (w.height, w.width) w.display() curses.napms(1000) curses.beep() w.clear() SA.refresh() curses.napms(2000)
def input(self, screen): screen.addstr("Enter name: ") self.__name = screen.getstr() screen.addstr("Enter ID: ") self.__ID = screen.getstr() screen.addstr("Enter number of credit: ") self.__credit = int(screen.getstr().decode()) screen.refresh() curses.napms(3000) screen.clear() screen.refresh()
def create_window(self, **kwargs): color_code = kwargs['color_code'] data = kwargs['data'] col_code_attr = ColorCode.get_color_pair(color_code) x = 3 y = self.get_max_height() // 2 - 1 self.on_attr(col_code_attr) self._window.addstr(y, x, f"{data} is set Successfully") self.off_attr(col_code_attr) self._window.refresh() curses.napms(1000)
def main(stdscr): global car_pos client = boto3.client('sagemaker-runtime') use_default_colors() stdscr.border() curs_set(0) stdscr.addstr(1, 1, "(r) for random road") stdscr.addstr(2, 1, "(s) for sine wave road") mode = stdscr.getch() stdscr.nodelay(True) for i in range(100): label = "1" # straight road_csv = draw_road(stdscr) napms(300) # ask sagemaker linear learner for the car direction body = ",".join(road_csv) response = client.invoke_endpoint( EndpointName='driving-endpoint', Body=body, ContentType='text/csv' ) # {"predictions": [{"score": [0.9913098216056824, 0.008546961471438408, 0.000143218640005216], "predicted_label": 0.0}]} interfence = json.loads(response['Body'].read()) label = int(interfence["predictions"][0]["predicted_label"]) if label == 0: # left car_pos-=1 if label == 2: # right car_pos+=1 stdscr.addstr(len(road_centers)+1, 2, "Sagemaker says: %s" % ["left ", "straight", "right "][label]) stdscr.refresh() road_csv.insert(0, label) training_csv.append(road_csv) pop = road_centers.pop() if mode == ord("s"): road_centers.insert(0, pop) else: first = road_centers[0] rnd = random.choice([0,1,2]) if rnd==0: road_centers.insert(0, first-1) if rnd==1: road_centers.insert(0, first) if rnd==2: road_centers.insert(0, first+1) stdscr.nodelay(False) stdscr.addstr(12, 1, "Press any key to quit") stdscr.getkey()
def save_config(self, stdscr): config.write_config(self.config_list) curses.noecho() stdscr.erase() try: stdscr.addstr( 1, 0, "SETTINGS SAVED! PULL CONFIG JUMPER TO GO BACK TO RUN MODE") except: pass stdscr.refresh() curses.napms(5000)
def simpletest(screen): import screen_area SA = screen_area.ScreenArea() w = Textfield(SA, rely=23, relx=6, width=15) w.value = "height: %s, width %s" % (w.height, w.width) w.edit() w.update() w2 = Textfield(SA, rely=20, relx=6, width=15) w.clear(usechar='x') w2.clear(usechar='x') SA.refresh() curses.napms(2000)
def input_fn(self): # auto controls self.stdscr.refresh() curses.napms(50) if self.paddle_x < self.ball_x: return 1 elif self.paddle_x > self.ball_x: return -1 else: return 0 # manual controls """
def input_number_course(): while True: sc.refresh() Num_course = int(sc.getstr().decode()) curses.init_pair(1, curses.A_BOLD, curses.A_UNDERLINE) sc.addstr("Invalid number\n", curses.color_pair(1)) sc.refresh() curses.napms(3000) sc.clear() sc.refresh() return Num_course
def draw_life(stdstr): for i in range(iterations): draw_grid() window.refresh() curses.napms(sleep_time) lifecycle(new_grid) curses.napms(2000) window.clear() curses.endwin()
def main_exit(screen): screen.border() fonts.tittle(screen, '~ O P C I O N E S ~') x2 = x screen.addstr(x2, 3, 'Parpadeo', curses.color_pair(2) | curses.A_BOLD) curses.napms(user.animation_config) screen.erase() screen.refresh() curses.endwin() options.main(5)
def show(self): try: while self.key_pressed != ord(QUIT_CHARACTER): self.screen.clear() self.key_pressed = self.screen.getch() self.show_text() self.screen.refresh() curses.napms(self.delay()) finally: curses.endwin()
def do_exit(self, msg = None, wait = 3): if msg: self.screen.clear() self.screen.addstr(1,1,'Exiting because: {}'.format(msg)) self.refresh_screen() wait = 3 while wait > 0: self.screen.addstr(2,1,str(wait)) self.refresh_screen() wait -= 1 curses.napms(1000) self.__exit_curses()
class outputs(): def ShowCourses(): py.addstr("Show lists of Courses:\n") py.refresh() for Course in Courses: py.addstr( "[CourseID: ] %s [CourseName: ] %s [CourseCredits: ] %s\n" % (Course.get_cid(), Course.get_name(), Course.get_credit())) py.refresh() def ShowStudent(): py.addstr("Show lists of student:\n") py.refresh() for Student in Students: py.addstr( "[Studentid: ] %s [StudentName: ] %s [StudentDOB: ] %s \n" % (Student.get_id(), Student.get_name(), Student.get_dob())) py.refresh() def ShowMarks(): py.addstr("Show lists of mark:\n") py.refresh() for mark in Mark: py.addstr( "[Mark_coursesid: ] %s [Mark_studentid: ] %s [Mark_mark: ] %s\n" % (mark.get_cid(), mark.get_id(), mark.get_marks())) py.refresh() def GPA_decending(): arr = np.array([Mark_gpa]) arr[::-1].sort() py.addstr("The list after sorting is %s: \n" % (arr)) py.refresh() def displaycenteroutline(infomation): row, colum = py.getmaxyx() Xrow = int(row / 3) Ycolumn = int(colum / 3) if infomation == "--- This is a Student management program ---": py.addstr(Xrow, Ycolumn, infomation, curses.A_BLINK) py.refresh() else: py.addstr(Xrow, Ycolumn, infomation, curses.A_BOLD) py.refresh() displaycenteroutline("---Hello friend---") py.refresh() curses.napms(1000) displaycenteroutline("This is a Student management program ") py.refresh() curses.napms(2000) py.clear() py.refresh()
def matrix(window): curses.start_color() #allow for color manipulation routines curses.use_default_colors() #use the terminals default colors curses.curs_set(0) window.clear() #clear the terminal window.refresh() #refresh the terminal height, width = window.getmaxyx( ) #get the height and width of the terminal characters = "abcdefghijklmnopqrstuvwxyz!@#$%^&*()_+-=[]{};:,<>./? " #list of characters to use (extra space chars to be chosen more frequently) #perform action until interupt (CNTR + C) while (True): for row in reversed( range(height - 1) ): #iterate through the matrix in reverse to shift items down the terminal for column in reversed(range(width)): if row == 0: #when we are at the top of the terminal string = window.instr( row + 1, column, 1) #collect the item below the cursor window.addstr( 0, width - 1, " ") #append a comparison byte string to the terminal comparison = window.instr( 0, width - 1, 1) #collect the comparison byte string window.move( row, column) #reset the cursor to the current row,column if string == comparison: #check to see if we have a " " below where we are more likely to append another if random.randint( 0, 15 ) == 0: #if " " was found, unlikely chance we would get soemthing other than " " window.addstr(row, column, random.choice( characters)) #append a new random char else: window.addstr(row, column, string) #append another " " else: window.addstr( row, column, random.choice(characters) ) #if " " is not found, append a new random character else: #when we are not at the top of the terminal string = window.instr(row - 1, column, 1) #collect the item to shift down window.move( row, column) #reset the cursor to the current row,column window.addstr(row, column, string) #shift the item down curses.napms(50) #wait for visual appeal window.refresh() #refresh the termianl to update display
def _main(screen): writer = Writer(screen) stat = Status(screen) key = KeyHandler(screen, stat) hsbc_logo_file = open('output.txt', 'r') for i, line in enumerate(hsbc_logo_file.readlines()): screen.addstr(i, 0, line) while True: if key.get(): break # terminal size will not be changed. canvas = Canvas(screen) # last_wave used to mark the matirx rain as TO BE STOPPED, # when all the nodes are expired, matrix rain stops. last_wave = False while True: if key.get(): # press any key in key list in the key.get() function will stop matix. last_wave = True canvas.last_wave() for col in canvas.columns: if col.timer == 0: col.spawn_node(canvas) col.timer -= 1 for node in canvas.nodes: writer.draw(node) node.y_coord += 1 # Mark old nodes for deletion if node.y_coord >= canvas.row_count: if node.white: node.white = False node.y_coord -= 1 else: node.expired = True canvas.nodes = [node for node in canvas.nodes if not node.expired] screen.refresh() curses.napms(key.delay) # wave_delay = 10 if last_wave and len(canvas.nodes) == 0: break tuanzi_logo_file = open('tuanzi.txt', 'r') for i, line in enumerate(tuanzi_logo_file.readlines()): screen.addstr(i, 0, line) while True: if key.get(): break
def run(): screen = crs.initscr() crs.start_color() crs.use_default_colors() if crs.can_change_color(): crs.init_color(1, 1000, 0, 0) crs.init_color(2, 0, 1000, 0) crs.init_color(3, 1000, 1000, 0) crs.init_color(4, 0, 0, 1000) crs.init_color(5, 1000, 500, 1000) crs.init_color(6, 500, 500, 1000) crs.init_color(7, 1000, 750, 325) crs.init_pair(1, -1, 1) crs.init_pair(2, -1, 2) crs.init_pair(3, -1, 3) crs.init_pair(4, -1, 4) crs.init_pair(5, -1, 5) crs.init_pair(6, -1, 6) crs.init_pair(7, -1, 7) crs.noecho() crs.cbreak() crs.curs_set(0) wTitle = crs.newwin(6, 19, 0, 4) wScore = crs.newwin(4, 17, 6, 5) wCntrl = crs.newwin(14, 23, 10, 2) wBoard = crs.newwin(24, 22, 0, 27) wBoard.keypad(True) wBoard.nodelay(True) wNextP = crs.newwin(7, 19, 0, 51) wStats = crs.newwin(17, 19, 7, 51) # Draw boarders of windows wTitle.border() wScore.border() wCntrl.border() wBoard.border() wNextP.border() wStats.border() wScore.addstr('HI', crs.color_pair(1)) wTitle.refresh() wScore.refresh() wCntrl.refresh() wBoard.refresh() wNextP.refresh() wStats.refresh() crs.napms(10000) crs.endwin()
def stucount(): scr.addstr("How many students we have?") scr.refresh() numos = int(scr.getstr().decode()) if numos <= 0: curses.init_pair(1, curses.COLOR_BLACK, curses.COLOR_WHITE) scr.addstr("Wrong number!\n", curses.color_pair(1)) scr.refresh() curses.napms(10000) scr.clear() scr.refresh() else: return numos
def __init__(self, stdscr): self.screen = stdscr self.height, self.width = self.screen.getmaxyx() self.new_win = curses.newwin(self.height, self.width, 0, 0) self.new_win.border() self.sub_win = SubWindow(self.new_win, 3, 0) self.new_win.refresh() self.sub_win.display() curses.napms(3000) curses.endwin()
def run(self): screen = curses.initscr() self.draw_borders(screen) self.draw_grid(screen) while self.life.is_changing and not self.life.is_max_generations_exceeded: self.life.step() self.draw_grid(screen) curses.napms(self.life.speed) screen.getkey() curses.endwin()
def input_number_course(): while True: py.refresh() Nco = int(py.getstr().decode()) if Nco <= 0: curses.init_pair(1, curses.COLOR_RED, curses.COLOR_WHITE) py.addstr("Does not exits!!!\n", curses.color_pair(1)) py.refresh() curses.napms(3000) py.clear() py.refresh() else: return Nco
def main(stdscr): gme = Ticker('GME') while True: output = str(gme) stdscr.clear() stdscr.addstr(0, 0, output) stdscr.refresh() if stdscr.getch() in [ord('q'), ord('Q')]: break curses.napms(500)
def run(self) -> None: screen = curses.initscr() # PUT YOUR CODE HERE # my_window = curses.newwin(15, 20, 0, 0) self.draw_borders(screen) while life.is_changing and not life.is_max_generations_exceed: life.step() self.draw_grid(screen) curses.napms(300) screen.addstr(self.life.rows + 2, 0, "Нажмите любую клавишу, чтобы выйти.") c = screen.getch() curses.endwin()