示例#1
0
def main(stdscr):
    curses.savetty()
    try:
        module_funcs(stdscr)
        window_funcs(stdscr)
    finally:
        curses.resetty()
示例#2
0
 def __init__(
     self,
     menu,
     description,
     title="Build system for MIREA education operation system - eduBian (c)2017 - 2018"
 ):
     curses.initscr()
     curses.savetty()
     curses.start_color()
     curses.setupterm()
     curses.init_pair(1, curses.COLOR_BLACK, curses.COLOR_CYAN)
     curses.cbreak()
     curses.noecho()
     curses.curs_set(0)
     self.screen = curses.initscr()
     self.screen.keypad(True)
     self.hT = curses.color_pair(1)
     self.nT = curses.A_NORMAL
     height, width = self.screen.getmaxyx()
     layer = [{"height": height}, {"width": width}, {"title": title}]
     self.menu = menu
     self.description = description
     self.screen.clear()
     self.screen.border(0)
     self.screen.refresh()
     self.position = 1
     self.str_count = 0
     self.display(layer, self.menu, self.description)
示例#3
0
文件: curses.py 项目: clandgraf/cui
    def initialize(self):
        self._color_index_map = DEFAULT_COLOR_INDEX_MAP.copy()
        self._old_signal_handler = None

        # Init Curses
        self._screen = curses.initscr()
        curses.savetty()
        curses.raw(1)
        curses.nonl()
        curses.noecho()
        curses.curs_set(0)
        self._screen.keypad(1)
        self._screen.timeout(0)
        self._core.add_exit_handler(self.close)

        # Init Colors
        curses.start_color()
        self._init_colors()

        # Init Symbols
        self.symbols = {
            symbols.SYM_VLINE: curses.ACS_VLINE,
            symbols.SYM_HLINE: curses.ACS_HLINE,
            symbols.SYM_LTEE: curses.ACS_LTEE,
            symbols.SYM_LLCORNER: curses.ACS_LLCORNER,
            symbols.SYM_RARROW: curses.ACS_RARROW,
            symbols.SYM_DARROW: curses.ACS_DARROW,  #ord('v'),
        }

        # Init Event Handling
        self._core.io_selector.register(sys.stdin, self._read_input)
        self._core.io_selector.register_async(TERMINAL_RESIZE_EVENT,
                                              self._handle_resize)
        self._old_signal_handler = signal.getsignal(signal.SIGWINCH)
        signal.signal(signal.SIGWINCH, self._handle_resize_sig)
示例#4
0
def main(stdscr):
    curses.savetty()
    try:
        module_funcs(stdscr)
        window_funcs(stdscr)
    finally:
        curses.resetty()
示例#5
0
 def save_mode(self):
     """Save the current terminal mode."""
     # Apparently this doesn't work?
     # curses.def_prog_mode()
     # self.mode = True
     curses.savetty()
     self.mode = True
示例#6
0
def main(stdscr):
	curses.savetty()
	try:
		logo(stdscr)
		w = xmms_main_window(stdscr)
		w.main_keyloop()
	finally:
		curses.resetty()
示例#7
0
def main(stdscr):
        curses.savetty()
        try:
                logo(stdscr)
                w = cxmms_window_manager(stdscr)
                w.keyloop()
        finally:
                curses.resetty()
示例#8
0
def main(stdscr):
    curses.savetty()
    try:
        module_funcs(stdscr)
        window_funcs(stdscr)
        test_userptr_without_set(stdscr)
    finally:
        curses.resetty()
示例#9
0
 def __setup_gui(self):
     """Initialize default curses settings, and fetches the screen size."""
     curses.start_color()
     curses.savetty()
     curses.noecho()
     curses.cbreak()
     curses.curs_set(0)
     self.screen.keypad(True)
     self.resize_event()
示例#10
0
def run(user, cmd, interactive=False):
    '''
    Run ``cmd`` as ``user``. If ``interactive`` is True, save any curses status
    and synchronously run the command in foreground. Otherwise, run the command
    in background, discarding any output.

    special user -2 means: current user
    '''
    prefix = []
    cur_uid = os.getuid()
    try:
        cur_user = pwd.getpwuid(cur_uid).pw_name
    except:
        cur_user = cur_uid

    if user != cur_user and user != -2:
        if cur_uid == 0:
            prefix = ['su', user]
        if user == 'root':
            prefix = ['sudo']
        else:
            prefix = ['sudo', '-u', user]

    if interactive:
        # Prepare screen for interactive command
        curses.savetty()
        curses.nocbreak()
        curses.echo()
        curses.endwin()

        # Run command
        pty.spawn(prefix+cmd)

        # Restore screen
        curses.start_color() # load colors
        curses.use_default_colors()
        curses.noecho()      # do not echo text
        curses.cbreak()      # do not wait for "enter"
        curses.curs_set(0)   # hide cursor
        curses.mousemask(curses.ALL_MOUSE_EVENTS)
        curses.resetty()
    else:
        with open('/dev/null', 'w') as dev_null:
            subprocess.Popen(
                prefix+cmd,
                stdout=dev_null,
                stderr=dev_null,
                close_fds=True,
            )
示例#11
0
def run(user, cmd, interactive=False):
    '''
    Run ``cmd`` as ``user``. If ``interactive`` is True, save any curses status
    and synchronously run the command in foreground. Otherwise, run the command
    in background, discarding any output.

    special user -2 means: current user
    '''
    prefix = []
    cur_uid = os.getuid()
    try:
        cur_user = pwd.getpwuid(cur_uid).pw_name
    except:
        cur_user = cur_uid

    if user != cur_user and user != -2:
        if cur_uid == 0:
            prefix = ['su', user]
        if user == 'root':
            prefix = ['sudo']
        else:
            prefix = ['sudo', '-u', user]

    if interactive:
        # Prepare screen for interactive command
        curses.savetty()
        curses.nocbreak()
        curses.echo()
        curses.endwin()

        # Run command
        pty.spawn(prefix + cmd)

        # Restore screen
        curses.start_color()  # load colors
        curses.use_default_colors()
        curses.noecho()  # do not echo text
        curses.cbreak()  # do not wait for "enter"
        curses.curs_set(0)  # hide cursor
        curses.mousemask(curses.ALL_MOUSE_EVENTS)
        curses.resetty()
    else:
        with open('/dev/null', 'w') as dev_null:
            subprocess.Popen(
                prefix + cmd,
                stdout=dev_null,
                stderr=dev_null,
                close_fds=True,
            )
示例#12
0
 def __init__(self):
     curses.setupterm()
     self.scr = curses.initscr()
     curses.savetty()
     # curses.def_shell_mode()
     curses.curs_set(0)
     # curses.start_color()
     curses.noecho()
     curses.cbreak()
     self.scr.scrollok(False)
     curses.def_prog_mode()
     self.scr.refresh()
     self.curses_module = curses
     self.last_time = time.monotonic()
     self.status_updates = True
示例#13
0
 def __init__(self):
     curses.setupterm()
     self.scr = curses.initscr()
     curses.savetty()
     #curses.def_shell_mode()
     curses.curs_set(0)
     #curses.start_color()
     curses.noecho()
     curses.cbreak()
     self.scr.scrollok(False)
     curses.def_prog_mode()
     self.scr.refresh()
     self.curses_module = curses
     self.last_time = time.monotonic()
     self.status_updates = True
示例#14
0
 def editor(self, i):
     # logger.debug("Before invoking editor")
     self.stdscr.keypad(0)
     curses.savetty()
     curses.echo()
     curses.nocbreak()
     curses.endwin()
     super().editor(i)
     curses.cbreak()
     curses.noecho()
     curses.resetty()
     self.stdscr.keypad(True)  # keys processed by curses (again)
     self.stdscr.clear()
     self.stdscr.refresh()
     # logger.debug("After invoking editor")
     return
示例#15
0
文件: moss.py 项目: pkozbial/moss
 def showCommand(self, force):
   if self._results == None:
     return FeedCmdResult.error('No results to show yet (use \'search\' command first).')
   if self._resultsFresh == False and not force:
     return FeedCmdResult.error('The query has been changed. To show the previous '+\
                                'results, use \'show!\' command.')
   mbox = mailbox.Maildir('.tmp.mail.dir', None, True)
   mbox.clear()
   for message in self._results:
     mbox.add(message)
   mbox.close()
   self._mainLayout.save()
   curses.savetty()
   os.system('mutt -f .tmp.mail.dir')
   self._mainLayout.restore()
   curses.resetty()
   return FeedCmdResult()
示例#16
0
def initGpio(firstrun=0):
    curses.savetty()  #Save screen

    #Init GPIO
    if not firstrun:
        GPIO.cleanup()
    GPIO.setmode(GPIO.BCM)
    GPIO.setwarnings(0)

    #Init GPIO pins, set event_detect callbacks, save initial states etc.
    for i,channel in enumerate(gpio_ch):
        if not gpio_inout[i]:
            GPIO.setup(channel, GPIO.IN, pull_up_down=GPIO.PUD_DOWN if gpio_pud[i] == 0 else GPIO.PUD_UP)
            GPIO.add_event_detect(channel, GPIO.BOTH, callback = gpio_callback, bouncetime = debounce)
            gpio_state[i] = GPIO.input(channel) # Primary state

    curses.resetty()  # Restore screen
示例#17
0
def initGpio(firstrun=0):
    curses.savetty()  #Save screen

    #Init GPIO
    if not firstrun:
        GPIO.cleanup()
    GPIO.setmode(GPIO.BCM)
    GPIO.setwarnings(0)

    #Init GPIO pins, set event_detect callbacks, save initial states etc.
    for i,channel in enumerate(gpio_ch):
        if not gpio_inout[i]:
            GPIO.setup(channel, GPIO.IN, pull_up_down=GPIO.PUD_DOWN if gpio_pud[i] == 0 else GPIO.PUD_UP)
            GPIO.add_event_detect(channel, GPIO.BOTH, callback = gpio_callback, bouncetime = debounce)
            gpio_state[i] = GPIO.input(channel) # Primary state

    curses.resetty()  # Restore screen
示例#18
0
文件: gpiotest.py 项目: kgbplus/queue
def initGpio():
    curses.savetty()
    #Init GPIO
    GPIO.cleanup()
    GPIO.setmode(GPIO.BCM)
    GPIO.setwarnings(0)
    for i in range(gpio_num):
        if (not gpio_inout[i]):
            GPIO.setup(gpio_ch[i],
                       GPIO.IN,
                       pull_up_down=GPIO.PUD_DOWN
                       if gpio_pud[i] == 0 else GPIO.PUD_UP)
            GPIO.add_event_detect(gpio_ch[i],
                                  GPIO.BOTH,
                                  callback=gpio_callback,
                                  bouncetime=debounce)
            gpio_state[i] = GPIO.input(gpio_ch[i])
    curses.resetty()
示例#19
0
文件: moss.py 项目: pkozbial/moss
 def showCommand(self, force):
     if self._results == None:
         return FeedCmdResult.error(
             'No results to show yet (use \'search\' command first).')
     if self._resultsFresh == False and not force:
         return FeedCmdResult.error('The query has been changed. To show the previous '+\
                                    'results, use \'show!\' command.')
     mbox = mailbox.Maildir('.tmp.mail.dir', None, True)
     mbox.clear()
     for message in self._results:
         mbox.add(message)
     mbox.close()
     self._mainLayout.save()
     curses.savetty()
     os.system('mutt -f .tmp.mail.dir')
     self._mainLayout.restore()
     curses.resetty()
     return FeedCmdResult()
示例#20
0
def init_ui(stdscreen):
    """
    initialize curses.
    """

    curses.curs_set(0)
    curses.start_color()
    curses.init_pair(1, curses.COLOR_BLACK, curses.COLOR_WHITE)
    curses.init_pair(2, curses.COLOR_BLACK, curses.COLOR_RED)
    curses.init_pair(3, curses.COLOR_BLACK, curses.COLOR_GREEN)
    curses.init_pair(4, curses.COLOR_BLACK, curses.COLOR_BLUE)
    curses.init_pair(5, curses.COLOR_BLACK, curses.COLOR_YELLOW)

    # curses configuration
    curses.savetty()  # save the terminal state
    curses.noecho()  # disable user input echo
    curses.cbreak()  # disable line buffering
    curses.curs_set(False)  # disable the cursor display
    stdscreen.keypad(True)
示例#21
0
 def rename_file(self, file):
     renamefile = self.tmpfile + "renamefile"
     with open(renamefile, 'w') as rnfile:
         rnfile.write(file)
     with open(renamefile, 'r') as rnfile:
         oldname = rnfile.readlines()[0]
     curses.endwin()
     curses.savetty()
     with open(renamefile, 'r') as rnfile:
         subprocess.run(["vim", renamefile])
         curses.resetty()
         self.stdscr.refresh()
         curses.curs_set(0)
         newname = rnfile.read().splitlines()[0]
         if newname in self.dir_contents:
             self.print_contents(newname + " already exists")
         elif oldname != newname and newname != "x":
             os.rename(oldname, newname)
             self.dir_contents[self.curr_pos] = newname
             self.print_contents(newname)
示例#22
0
      print indice, ",".join([node_shards.get(n, "") for n in node_hostnames_list])
  if options.show_indices_routing_csv:
    print "Total Shards,",",".join([str(node_total_shards.get(n, "")) for n in node_hostnames_list])
  #pprint(nodes)
 
def doc_counts(indices):
  es_info = requests.get("http://%s/%s/_status" % (cluster, indices)).json()
  idxdocs = []
  for i in es_info['indices'].keys():
    idxdocs.append((i, es_info['indices'][i]['docs']['num_docs'], es_info['indices'][i]['store']['size_in_bytes']))
  return idxdocs

# I just felt like messing around with curses...
if soopretty:
  myscreen = curses.initscr()
  curses.savetty()
  myscreen.border()
  myscreen.scrollok(True) 
  curses.noecho()

def pp(line):
  if soopretty:
    myscreen.addstr(line+"\n")
  else:
    print line

def index_documents():
	match_indices = ",".join(indices_by_pattern(indice_pattern))
	dc = doc_counts(match_indices)
	dc.sort(key=lambda x: x[0])
 
示例#23
0
    def __init__(self, y=15, x=15, debug=True):
        if debug:
            self.log = open("admm.log", 'a+')

        maze = {}
        self.maxY = y - 1
        self.maxX = x - 1
        self.minY = self.minX = 0
        self.visited = 0

        locale.setlocale(locale.LC_ALL, '')
        code = locale.getpreferredencoding()
        self.debug = debug
        if debug:
            print "Hello there! deubg is ", debug
        # Setup Player
        self.setScore(0)
        # pizza
        player = u"\U0001f355"

        #house
        self.exit = u"\U0001f3e0"

        # Setup Screen
        stdscr = curses.initscr()
        curses.savetty(
        )  #make sure we can put the screen back the way we found it
        curses.noecho()  #prevent keypresses appearing on screen
        curses.cbreak()  #interpret input with out return
        stdscr.keypad(1)  #everyone loves the keypad
        stdscr.clearok(1)  #allow the screen to be cleared
        curses.curs_set(0)  #hide the caret

        stdscr.clear()
        stdscr.refresh()

        self.minX = minX = 0
        #how far to the right we can go.
        #Leaving room for messages.
        self.maxX = maxX = stdscr.getmaxyx()[1] - 15

        self.minY = minY = 0
        ##how far down we can go
        #leaving room for messages
        self.maxY = maxY = stdscr.getmaxyx()[0] - 5

        # setup maze
        for cols in range(maxY):
            maze[cols] = {}
            for rows in range(maxX):
                maze[cols][rows] = {}
                maze[cols][rows]['visited'] = False
                self.visited += 1
                maze[cols][rows]['wall'] = True

        self.maze = maze
        self.__get_start__()
        self.__generate_maze__(self.startY, self.startX)

        charPos = [self.lastY, self.lastX]

        stdscr.clear()
        stdscr.refresh()
        # begin main while

        moveTest = True
        # charPos = {'y':0,'x':0}
        while moveTest:

            stdscr.clear()

            for cols in self.maze:
                for rows in self.maze[cols]:
                    if self.maze[cols][rows]['wall']:
                        stdscr.addstr(cols, rows, "#")
            stdscr.addstr(charPos[0], charPos[1] - 1, player.encode("utf-8"))
            stdscr.addstr(self.startY, self.startX, self.exit.encode("utf-8"))

            stdscr.refresh()

            move = stdscr.getch()
            if move == 113:
                moveTest = False
            elif move == curses.KEY_RIGHT:
                if self.maze[charPos[0]][charPos[1] + 1]['wall'] == False:
                    charPos[1] += 1
            elif move == curses.KEY_LEFT:
                if self.maze[charPos[0]][charPos[1] - 1]['wall'] == False:
                    charPos[1] -= 1
            elif move == curses.KEY_UP:
                if self.maze[charPos[0] - 1][charPos[1]]['wall'] == False:
                    charPos[0] -= 1
            elif move == curses.KEY_DOWN:
                if self.maze[charPos[0] + 1][charPos[1]]['wall'] == False:
                    charPos[0] += 1

        # end main while

        time.sleep(1)
        ##put it all back
        curses.resetty()
        curses.endwin()

        if debug:
            self.log.close()
示例#24
0
def main(scr):
    reset(scr)
    init_colors()
    display_logo(scr)
    drawing = Drawing(scr)
    tutor = Tutor(scr)
    save_dir = directory_setup()
    pen_tips = " ~`!@#$%^&*()-_+=vvxxoo|\/[]{}'.:<>\""

    while True:
        c = scr.getch()
        if c == ord("q"):  # QUIT
            break
        elif c == curses.KEY_RESIZE:
            drawing.recenter()
            continue
        elif c == curses.KEY_UP:
            drawing.move_by(-1, 0)
        elif c == curses.KEY_DOWN:
            drawing.move_by(1, 0)
        elif c == curses.KEY_RIGHT:
            drawing.move_by(0, 1)
        elif c == curses.KEY_LEFT:
            drawing.move_by(0, -1)
        elif c == ord("c"):  # CHANGE COLORS
            drawing.color_pair = (drawing.color_pair + 1) % 8
            tutor.change_color()
        elif c == ord("n"):  # NEW DRAWING
            reset(scr)
            drawing = Drawing(scr)
            tutor.new()
            continue  # skip drawing: the new drawing should be empty
        elif c == ord("p"):  # PEN UP/DOWN
            drawing.pen_down = not drawing.pen_down
            tutor.pen()
        elif c == ord("e"):  # ERASE
            tutor.erase()
            drawing.erase_last()
            continue  # skip drawing: that would negate the erase
        elif c == ord("r"):  # REPLAY CURRENT DRAWING
            tutor.message("OK, now it's my turn!")
            drawing.replay()
            continue  # skip drawing: that would add to it
        elif c == ord("s"):  # SAVE CURRENT DRAWING
            try:
                drawing.save(save_dir)
                tutor.message("I saved your drawing!")
            except IOError:
                tutor.message(
                    "Sorry, something went wrong.\nI couldn't save this drawing."
                )
        elif c == ord("l"):  # LOAD SAVED DRAWING
            try:
                drawing = Drawing(scr)
                tutor.message(
                    "Here's a drawing you made!\n(Or someone made for you!)")
                drawing.load_random(save_dir)
            except IndexError:
                tutor.message(
                    "There are no drawings to load!\nYou should save one first."
                )
            continue  # skip drawing: the cursor hasn't moved

        elif c == ord("D"):  # DELETE
            if drawing.fname:
                os.remove(drawing.fname)
                tutor.message("Deleted %s" % drawing.fname)
                reset(scr)
                drawing = Drawing(scr)

        elif c == ord("?") or c == ord("h"):  # HELP
            tutor.help()
        elif c in map(ord, pen_tips):  # PEN TIP
            drawing.pen_tip = chr(c)
        elif c in map(ord, "01234567"):  # COLOR SELECTION
            drawing.color_pair = int(chr(c))
        elif c == curses.KEY_F3:  # DEBUG
            # save terminal state for later:
            curses.savetty()
            # return to shell mode for debug session:
            scr.move(0, 0)
            curses.reset_shell_mode()
            scr.refresh()
            import pdb
            pdb.set_trace()
            # when debugging is finished, restore the previous state:
            curses.resetty()
            reset(scr)
            drawing.recenter()

        # draw a new 'pixel' at the current location with the current pen tip,
        # if the pen is down:
        drawing.draw()
    def run(self):
        try:
            while True:
                #print 'Is the queue empty?: {}'.format(self.qscreen.empty())
                if not self.qscreen.empty():
                    order = self.qscreen.get()
                    #self.logfile.write('Receiving the order'+order+'\n')
                    if order == 'Start':
                        stdscr = curses.initscr()
                        curses.savetty()
                        curses.start_color()
                        curses.use_default_colors()
                        self.screen = stdscr
                        curses.init_pair(1, curses.COLOR_GREEN, -1)
                        curses.init_pair(2, curses.COLOR_RED, -1)
                        curses.init_pair(3, curses.COLOR_BLUE, -1)
                        curses.init_pair(4, curses.COLOR_WHITE, -1)
                        self.screen.bkgd(' ', curses.color_pair(1))
                        self.screen.bkgd(' ')
                        curses.noecho()
                        curses.cbreak()
                        self.screen.keypad(1)
                        # curses.curs_set. 0 means invisible cursor, 1 visible, 2 very visible
                        curses.curs_set(0)
                        self.screen.addstr(0,0, 'Live Stream', curses.A_BOLD)
                        self.screen.refresh()
                        self.qscreen.task_done()

                    elif order == 'Stop':
                        self.screen.addstr(0,0, 'Press any key to go back to stf screen...                                                                   ', curses.A_BOLD)
                        self.screen.getstr(0,0, 15)
                        curses.nocbreak()
                        self.screen.keypad(0)
                        curses.echo()
                        curses.curs_set(1)
                        stdscr.refresh()
                        # close
                        self.qscreen.task_done()
                        curses.resetty()
                        self.f.close()
                        return
                    else:
                        #self.screen.addstr(0,50, 'Receiving Data')
                        self.screen.refresh()
                        # Get the screen size
                        (x_max, y_max) = self.screen.getmaxyx()
                        # The order 
                        orig_tuple = order
                        tuple_id = orig_tuple.get_id()
                        # Get the amount of letters that fit on the screen
                        state = orig_tuple.get_state()[-(y_max-self.y_min):]
                        tuple = self.get_tuple(tuple_id)
                        # Update the status bar
                        if int(tuple['x_pos']) < x_max - 3: 
                            self.screen.addstr(0,20,tuple_id + "                            ", curses.A_BOLD)
                            self.screen.refresh()
                            #self.screen.addstr(int(tuple['x_pos']), int(tuple['y_pos']), state, tuple['color'] | curses.A_BOLD)
                            #if int(tuple['x_pos']) <= xmax:
                            self.screen.addstr(int(tuple['x_pos']), int(tuple['y_pos']), state, tuple['color'])
                            #tuple['y_pos'] += len(state)
                            self.screen.refresh()
                            self.qscreen.task_done()
        except KeyboardInterrupt:
            curses.nocbreak()
            self.screen.keypad(0)
            curses.echo()
            curses.curs_set(1)
            curses.resetty()
            self.screen.refresh()
        except Exception as inst:
            print '\tProblem with Screen()'
            print type(inst)     # the exception instance
            print inst.args      # arguments stored in .args
            print inst           # __str__ allows args to printed directly
            sys.exit(1)
示例#26
0
	def __init__(self, score=0,debug=False):
		"""
			admm started out as JUST the maze maker (ADvanced Maze Maker)
			but it sort of spiraled out of control. It is currently the 
			main game loop as well. I am not sure if I will ever change that.
			It takes a score and a debug value.
			I noticed that debug was, possibly, leading to segfaults...

			Inputs: int: 		score 
					boolean:	debug
			Output: Not really much

		"""
		self.debug = debug
		self.log = logger.Logger("admm.log")

		
		maze = {}
		# self.maxY = y-1
		# self.maxX = x-1
		# self.minY = self.minX = 0
		self.visited = 0

		locale.setlocale(locale.LC_ALL, '')
		code = locale.getpreferredencoding()
		self.debug = debug
		if debug :
			print "Hello there! deubg is ", debug
		# Setup Player
		
		# pizza
		# player =	u"\U0001f355"

		# p1 = {
		# 		'player':player,
		# 		'inventory':{},
		# 		'items':{},
		# 		'sight': 3
		# 	}

		self.score = score
		p1 = player.Player()
		p1.addItem('bombs',3)
		self.__setScore__(self.score,p1)

		self.log._log(p1)
		
		# exit icon
		#red circle?
		# self.exit =u"\U00002B55"
		#hot springs
		# self.exit =u"\U00002668"
		#house
		# self.exit = u"\U0001f3e0"
		#blue thing
		self.exit = u"\U0001f4a0"
		# arrow?
		# self.exit = u"\U000023eb"

		#wall Icon
		self.wall = "#"

		# self.wall = u"\U00002B1C"

		# Setup Screen
		stdscr = curses.initscr()
		curses.savetty() #make sure we can put the screen back the way we found it
		curses.noecho() #prevent keypresses appearing on screen
		curses.cbreak() #interpret input with out return
		stdscr.keypad(1) #everyone loves the keypad
		stdscr.clearok(1) #allow the screen to be cleared
		curses.curs_set(0) #hide the caret
		stdscr.border(0)

		curses.start_color()

		keypresses = { 
						'bomb'  : 'b'
						,'quit' : 'q'
						,'North': 'w'
						,'East' : 'd'
						,'West' : 'a'
						,'South': 's'
						# ,'menu':'m'
					}

		self.items= { 	'health':{'icon':u"\U0001f493",'position':1,'max':100,'current':100},
						'money':{'icon':u"\U0001f4b0",'position':4,'max':100000,'current':0},
						'food':{'icon':u"\U0001f371",'position':7,'max':10,'current':0},
						'bomb':{'icon':u"\U0001F4a3",'position':10,'max':10,'current':3,'timer':4,'action':self.__get_bomb__,'score':5}
				 	}
		# p1['items'] = self.items



		self.enemies = {}
		# used for placing on screen bombs
		sbomb = {}
		rem_bomb = []

		stdscr.clear()
		stdscr.refresh()

		self.minX = minX	= 0
		#how far to the right we can go.
		#Leaving room for messages.
		self.maxX = maxX	= stdscr.getmaxyx()[1] -15

		self.minY = minY	= 0
		##how far down we can go
		#leaving room for messages
		self.maxY = maxY	= stdscr.getmaxyx()[0] 


		# Room stuff
		self.maxRoomSize = 4
		self.roomY = []
		self.roomX = []
		for rooms in range(int((self.maxX*.25))):
			self.roomY += [random.choice(range(self.maxY))]
			self.roomX += [random.choice(range(self.maxX))]
		if debug:
			self.log._log("setting room up\nroomY numbers",getframeinfo(currentframe()).lineno,"low")
			self.log._log(json.dumps(self.roomY),getframeinfo(currentframe()).lineno,"low")
			

		# setup maze
		# 
		for cols in range(maxY):
			maze[cols] = {}
			
			for rows in range(maxX):
				maze[cols][rows] = {}
				maze[cols][rows]['wall'] = True
				maze[cols][rows]['visited'] = False
				maze[cols][rows]['checked'] = False
				maze[cols][rows]['contains'] = {}
				self.visited += 1


		self.maze = maze
		self.__get_start__()
		self.maze[self.startY][self.startX]['contains'] = "exit"
		self.__generate_maze__(self.startY,self.startX)

		self.__make_room__(self.startY,self.startX,3)

		self.__get_player_start__()

		charPos = [self.lastY,self.lastX]
		self.__make_room__(charPos[0],charPos[1],3)

		self.__place_items__()

		# self.__hider__()
			
		#self.__reveal__(charPos[0],charPos[1],p1['sight'])

		stdscr.clear()
		stdscr.refresh()
		# begin main while

		# OH my goodness this is such a hack
		# this started life as a way to test character movement...
		# it is currently the main game loop... >_<

		self.moveTest = True
		# charPos = {'y':0,'x':0}
		while self.moveTest:

			stdscr.clear()

			for cols in self.maze:
				for rows in self.maze[cols]:
					if self.maze[cols][rows]['wall'] :
						stdscr.addstr(cols,rows,self.wall.encode("utf-8"),curses.A_DIM)
					else:
						if self.maze[cols][rows]['checked']:
							stdscr.addstr(cols,rows,".",curses.A_DIM)
						else :
							stdscr.addstr(cols,rows," ",curses.A_DIM)
					for inv in self.maze[cols][rows]['contains']:
						try:
							if inv in self.items and self.maze[cols][rows]['contains'][inv]:
								stdscr.addstr(cols,rows,self.items[inv]['icon'].encode("utf-8"),curses.A_NORMAL)
						except Exception as e:
							# print  self.maze[cols][rows]['contains']
							msg = "inventory is {0}".format(self.maze[cols][rows]['contains'])
							
							self.log._err(e,msg,"219","medium")
			
			# Drawing the player character.
			# eventually the charPos should PROBABLY be contained in the 
			# player object... I will add it to the list.
			stdscr.addstr(charPos[0],charPos[1]-1,p1.icon.encode("utf-8"))
			
			# display side items
			stdscr.addstr(self.minY,self.maxX+2,"Score")
			stdscr.addstr(self.minY+1,self.maxX +2,str(p1.score))
			for item in items.getItems():
				posY = self.minY + items.getItems()[item]['position'] + 3
				posX = self.maxX + 2  #guh magic number

				# Ditching this log statement because I think I fixed it...
				# msg = "Trying to get the inventory to display properly...\n"
				# msg += " p1.inventory == {0}".format(p1.inventory) 
				# self.log._log(msg,226)
				values = str(p1.inventory[item]['quantity'])
				values += "/"
				values += str(items.getItems()[item]['max'])

				name =  item
				name += " "
				name += items.getItems()[item]['icon']

				stdscr.addstr(posY,posX,name.encode("utf-8"))
				stdscr.addstr(posY+1,posX,values.encode("utf-8"))

				# okay here we are getting the list of keypresses.
				# one day I might add standard wasd keys for movement... 
				# note the offset for maxY...
				instOffset = len(keypresses)+1
				stdscr.addstr(self.maxY-instOffset,self.maxX+1, "Controls:")
				# self.log._log("offset = {0}".format(instOffset))
				for k in keypresses:
					instOffset -= 1
					cy = self.maxY-instOffset
					cx = self.maxX+2
					ctrl = "{0} = {1}".format(keypresses[k],k)
					# self.log._log(ctrl)
					stdscr.addstr(cy,cx,ctrl.encode("utf-8"))


			# Draw the exit
			stdscr.addstr(self.startY,self.startX,self.exit.encode("utf-8"), curses.A_NORMAL)

			# this should probably be its own functions
			# Currently this is how to calculate bomb detonations..
			# it is REALLY hacky.
			for b in sbomb:
				sbomb[b]['counter'] -= 1
				if sbomb[b]['counter'] < 0:
					rem_bomb +=[b]
			if rem_bomb:
				for b in rem_bomb:
					self.__det_bomb(sbomb[b],stdscr)
					del sbomb[b]
				rem_bomb = []
			if sbomb:						
				for b in sbomb:
					stdscr.addstr(sbomb[b]['y'],sbomb[b]['x'],self.items['bomb']['icon'].encode("utf-8"), curses.A_BLINK)
					stdscr.addstr(sbomb[b]['y'],sbomb[b]['x']+1,str(sbomb[b]['counter']))

			# okay we have drawn everything, time to make it show up.
			stdscr.refresh()

			# this is the movement loop.
			# I suspect there is a prettier way to do this but...

			move = stdscr.getch()
			if move == ord('q') or move == ord('Q') :
				self.moveTest = False
			elif move == ord('b') or move == ord('B') :
				self.__place_bomb__(charPos[0],charPos[1],sbomb,p1)

			elif move == curses.KEY_RIGHT or move == ord('d'):
				if self.maze[charPos[0]][charPos[1]+1]['wall'] == False :
					charPos[1] += 1
			elif move == curses.KEY_LEFT or move == ord('a'):
				if self.maze[charPos[0]][charPos[1]-1]['wall'] == False :
					charPos[1] -= 1
			elif move == curses.KEY_UP or move == ord('w'):
				if self.maze[charPos[0]-1][charPos[1]]['wall'] == False :
					charPos[0] -= 1
			elif move == curses.KEY_DOWN or move == ord('s'):
				if self.maze[charPos[0]+1][charPos[1]]['wall'] == False :
					charPos[0] += 1
			elif move == ord('c'):
				window = self.__get_window__('medium')
				combat.Combat(p1,enemy.Enemy(-1,p1.level),window)
			
			# This is currently disabled. 
			# there was a time where I had sight radius implemented.
			# that time may come again.
			# self.__reveal__(charPos[0],charPos[1],p)
			
			# check to see if there is anything in our cell.
			# I might make this check adjacent cells.. I might not.
			self.__cell_check__(charPos[0],charPos[1],p1)

			self.score = p1.score

		# end main while

		# time.sleep(1)
		
		##put it all back
		# The resetty() returns the terminal to standard 
		curses.resetty()
		# kill the window.
		curses.endwin()
def doKeyEvent(key):
    if key == '\x00' or key == '\xe0': # non ASCII key
       key = screen.getch() # fetch second character
    screen.addstr(str(key)+' ')

def doQuitEvent(key):
    c.resetty() # set terminal settings
    c.endwin()  # end curses session
    raise SystemExit


# clear the screen of clutter, save current settings, stop characters auto 
# echoing to screen and then tell user what to do to quit

screen = c.initscr()
c.savetty()
c.noecho()
screen.addstr("Hit space to end...\n")

# Now mainloop runs "forever"
while True:
     ky = screen.getch()
     if ky != -1:
       # send events to event handling functions
       if ky == ord(" "): # check for quit event
	 doQuitEvent(ky)
       else: 
	 doKeyEvent(ky)

c.endwin()
示例#28
0
文件: moss.py 项目: pkozbial/moss
 def save(self):
     curses.savetty()
示例#29
0
    def execute(self, args):
        files = args.files

        if not files:
            files = find_files_of_type(os.path.realpath('.'), 'tex')

        ignoredb = self.config.get('acronyms', 'ignoredb')

        ignored = set()

        if os.path.exists(ignoredb):
            with open(ignoredb) as fh:
                for line in fh:
                    line = line.strip()
                    if line:
                        ignored.add(line)

        stdscr = curses.initscr()
        curses.savetty()
        curses.noecho()
        curses.cbreak()
        curses.curs_set(0)

        for f in files:
            with open(f) as fh:
                self.replacements = []
                contents = fh.read()
                for m in re.finditer(self.acronym_regex, contents):
                    ms, me = m.start(1), m.end(1)
                    token = contents

                    abbr = token[ms:me]
                    if abbr.endswith('s'):
                        abbr = abbr[:-1]
                    if abbr in ignored:
                        continue

                    line = contents.count("\n", 0, ms)

                    max_context = 20
                    prefix = postfix = ''

                    # Isolate a single line
                    cs = contents.rfind("\n", 0, ms) + 1
                    ce = contents.find("\n", me)

                    if ms - cs > max_context:
                        cs = ms - max_context
                        cs = contents.rfind(" ", 0, cs) + 1
                        prefix = '...'

                    if ce - me > max_context:
                        ce = me + max_context
                        ce = contents.find(" ", ce)
                        postfix = '...'

                    char = ms - cs

                    ms -= cs
                    me -= cs

                    token = token[cs:ce]

                    self.print_token_color(stdscr, f, token, line, char,
                                           ms, me, prefix, postfix)

                    callbacks = {
                        'l': self.replace_lower,
                        'u': self.replace_upper,
                        'p': self.replace_lower_plural,
                        'j': self.replace_upper_plural,
                    }

                    try:
                        c = stdscr.getch()
                        try:
                            callback = callbacks[chr(c)]
                        except (KeyError, ValueError):
                            if c == ord('f'):
                                break
                            else:
                                continue
                        else:
                            callback(contents, m.start(1), m.end(1))
                    except KeyboardInterrupt:
                        curses.resetty()
                        curses.nocbreak()
                        curses.echo()
                        curses.endwin()
                        return

            if self.replacements:
                for s, e, string in reversed(self.replacements):
                    contents = contents[:s] + string + contents[e:]
                with open(f, 'w') as fh:
                    fh.write(contents)
示例#30
0
|____/ \___/|_|  |_|_____|
                          
__     ___    ____  ___    _    ____  _     _____ ____  
\ \   / / \  |  _ \|_ _|  / \  | __ )| |   | ____/ ___| 
 \ \ / / _ \ | |_) || |  / _ \ |  _ \| |   |  _| \___ \ 
  \ V / ___ \|  _ < | | / ___ \| |_) | |___| |___ ___) |
   \_/_/   \_\_| \_\___/_/   \_\____/|_____|_____|____/ 

'''


buttonPressed = 0 #timer for button held down > 5 seconds, trigger shutdown
encoderEvent = time.time() -5  #encoder event paused subpatch menu
patchRunning = 0
pixel = 0
ORIGTTY = curses.savetty()
ORIGPROG = curses.def_shell_mode()
def invertline(a,t,d,s):
	menu.highlight(d[0])
	menu.update()
	menu.show()
def graphicsUpdate(a,t,d,s):
	#bash('setfont /usr/share/organelle/configs/pixel.psfu') #or you'll error out
	graphics.updateG() #push new pad to screen
	#graphics.show()
	
def dummyShow():
	dummy.erase()
	dummy.updateG()
	dummy.show()
def graphicsWave(a,t,d,s):
	def __init__(self, debug=True):
		
		locale.setlocale(locale.LC_ALL, '')
		code = locale.getpreferredencoding()
		self.debug = debug
		if debug :
			print "Hello there! deubg is ", debug
		# Setup Player
		self.setScore(0)
		
		# Setup Screen
		stdscr = curses.initscr()
		curses.savetty() #make sure we can put the screen back the way we found it
		curses.noecho() #prevent keypresses appearing on screen
		curses.cbreak() #interpret input with out return
		stdscr.keypad(1) #everyone loves the keypad
		stdscr.clearok(1) #allow the screen to be cleared
		curses.curs_set(0) #hide the caret

		self.minX = minX	= 0
		#how far to the right we can go.
		#Leaving room for messages.
		self.maxX = maxX	= stdscr.getmaxyx()[1] -15

		self.minY = minY	= 0
		##how far down we can go
		#leaving room for messages
		self.maxY = maxY	= stdscr.getmaxyx()[0] -5

		self.maze = {}
		self.minY = self.minX = 0
		self.visited = 0
		for row in range(maxY):
			self.maze[row] = {}
			for col in range(maxX):
				self.maze[row][col] = {}
				self.maze[row][col]["visited"] = False
				self.maze[row][col]["contains"] = {}
				self.visited += 1
				self.maze[row][col]["wall"] = True

		self.__get_start__()
		self.__generate_maze__(self.startY,self.startX)
		stdscr.clear()
		stdscr.refresh()
		# print self.maze

		
		# item = "0"
		# for y in range(maxY):
		# 	for x in range(maxX):
		# 		stdscr.addstr(y,x,item.encode("utf-8"))
		# 		stdscr.refresh()
		# 		time.sleep(0.001)
		# 		# stdscr.clear()

		moveTest = True
		charPos = {'y':0,'x':0}
		while moveTest:
			move = stdscr.getch()
			if move == 113 : 
				moveTest = False
			elif move == curses.KEY_RIGHT:
				charPos['x'] += 1
			elif move == curses.KEY_LEFT:
				charPos['x'] -= 1
			elif move == curses.KEY_UP:
				charPos['y'] -= 1
			elif move == curses.KEY_DOWN:
				charPos['y'] += 1 
			stdscr.clear()
			stdscr.addstr(charPos['y'],charPos['x']-1,item.encode("utf-8"))
			stdscr.refresh()


		time.sleep(1)
		##put it all back
		curses.resetty()
		curses.endwin()
		



		return None
    def __init__(self, debug=True):

        locale.setlocale(locale.LC_ALL, '')
        code = locale.getpreferredencoding()
        self.debug = debug
        if debug:
            print "Hello there! deubg is ", debug
        # Setup Player
        self.setScore(0)

        # Setup Screen
        stdscr = curses.initscr()
        curses.savetty(
        )  #make sure we can put the screen back the way we found it
        curses.noecho()  #prevent keypresses appearing on screen
        curses.cbreak()  #interpret input with out return
        stdscr.keypad(1)  #everyone loves the keypad
        stdscr.clearok(1)  #allow the screen to be cleared
        curses.curs_set(0)  #hide the caret

        self.minX = minX = 0
        #how far to the right we can go.
        #Leaving room for messages.
        self.maxX = maxX = stdscr.getmaxyx()[1] - 15

        self.minY = minY = 0
        ##how far down we can go
        #leaving room for messages
        self.maxY = maxY = stdscr.getmaxyx()[0] - 5

        self.maze = {}
        self.minY = self.minX = 0
        self.visited = 0
        for row in range(maxY):
            self.maze[row] = {}
            for col in range(maxX):
                self.maze[row][col] = {}
                self.maze[row][col]["visited"] = False
                self.maze[row][col]["contains"] = {}
                self.visited += 1
                self.maze[row][col]["wall"] = True

        self.__get_start__()
        self.__generate_maze__(self.startY, self.startX)
        stdscr.clear()
        stdscr.refresh()
        # print self.maze

        # item = "0"
        # for y in range(maxY):
        # 	for x in range(maxX):
        # 		stdscr.addstr(y,x,item.encode("utf-8"))
        # 		stdscr.refresh()
        # 		time.sleep(0.001)
        # 		# stdscr.clear()

        moveTest = True
        charPos = {'y': 0, 'x': 0}
        while moveTest:
            move = stdscr.getch()
            if move == 113:
                moveTest = False
            elif move == curses.KEY_RIGHT:
                charPos['x'] += 1
            elif move == curses.KEY_LEFT:
                charPos['x'] -= 1
            elif move == curses.KEY_UP:
                charPos['y'] -= 1
            elif move == curses.KEY_DOWN:
                charPos['y'] += 1
            stdscr.clear()
            stdscr.addstr(charPos['y'], charPos['x'] - 1, item.encode("utf-8"))
            stdscr.refresh()

        time.sleep(1)
        ##put it all back
        curses.resetty()
        curses.endwin()

        return None
示例#33
0
import curses
import time

#init curses
stdscr = curses.initscr()
curses.savetty()

max_rows = curses.LINES - 1
max_cols = curses.COLS - 1


def print_table(draw_table):
    curses.curs_set(False)
    stdscr.refresh()
    for x in range(len(draw_table)):
        for y in range(len(draw_table[0])):
            stdscr.addstr(x, y, draw_table[x][y])

    stdscr.nodelay(1)  # Don't block waiting for input.
    c = stdscr.getch(
    )  # Get char from input.  If none is available, will return -1.
    if c == 3:
        raise KeyboardInterrupt
    else:
        stdscr.nodelay(0)


def generate_table(rows, cols):
    # directions
    RIGHT = 1
    DOWN = 2
示例#34
0
#
示例#35
0
文件: moss.py 项目: pkozbial/moss
 def save(self):
   curses.savetty()
示例#36
0
#
示例#37
0
    def run(self):
        try:
            while True:
                #print 'Is the queue empty?: {}'.format(self.qscreen.empty())
                if not self.qscreen.empty():
                    order = self.qscreen.get()
                    #self.logfile.write('Receiving the order'+order+'\n')
                    if order == 'Start':
                        stdscr = curses.initscr()
                        curses.savetty()
                        curses.start_color()
                        curses.use_default_colors()
                        self.screen = stdscr
                        curses.init_pair(1, curses.COLOR_GREEN, -1)
                        curses.init_pair(2, curses.COLOR_RED, -1)
                        curses.init_pair(3, curses.COLOR_BLUE, -1)
                        curses.init_pair(4, curses.COLOR_WHITE, -1)
                        self.screen.bkgd(' ', curses.color_pair(1))
                        self.screen.bkgd(' ')
                        curses.noecho()
                        curses.cbreak()
                        self.screen.keypad(1)
                        # curses.curs_set. 0 means invisible cursor, 1 visible, 2 very visible
                        curses.curs_set(0)
                        self.screen.addstr(0,0, 'Live Stream', curses.A_BOLD)
                        self.screen.refresh()
                        self.qscreen.task_done()

                    elif order == 'Stop':
                        self.screen.addstr(0,0, 'Press any key to go back to stf screen...                                                                   ', curses.A_BOLD)
                        self.screen.getstr(0,0, 15)
                        curses.nocbreak()
                        self.screen.keypad(0)
                        curses.echo()
                        curses.curs_set(1)
                        stdscr.refresh()
                        # close
                        self.qscreen.task_done()
                        curses.resetty()
                        self.f.close()
                        return
                    else:
                        #self.screen.addstr(0,50, 'Receiving Data')
                        self.screen.refresh()
                        # Get the screen size
                        (x_max, y_max) = self.screen.getmaxyx()
                        # The order 
                        orig_tuple = order
                        tuple_id = orig_tuple.get_id()
                        # Get the amount of letters that fit on the screen
                        state = orig_tuple.get_state()[-(y_max-self.y_min):]
                        tuple = self.get_tuple(tuple_id)
                        # Update the status bar
                        if int(tuple['x_pos']) < x_max - 3: 
                            self.screen.addstr(0,20,tuple_id + "                            ", curses.A_BOLD)
                            self.screen.refresh()
                            #self.screen.addstr(int(tuple['x_pos']), int(tuple['y_pos']), state, tuple['color'] | curses.A_BOLD)
                            #if int(tuple['x_pos']) <= xmax:
                            self.screen.addstr(int(tuple['x_pos']), int(tuple['y_pos']), state, tuple['color'])
                            #tuple['y_pos'] += len(state)
                            self.screen.refresh()
                            self.qscreen.task_done()
        except KeyboardInterrupt:
            curses.nocbreak()
            self.screen.keypad(0)
            curses.echo()
            curses.curs_set(1)
            curses.resetty()
            self.screen.refresh()
        except Exception as inst:
            print '\tProblem with Screen()'
            print type(inst)     # the exception instance
            print inst.args      # arguments stored in .args
            print inst           # __str__ allows args to printed directly
            sys.exit(1)