Exemple #1
0
def worldLoop(window):
    # Add room, player, and npc to world
    room = Room.loadRoom('great_hall')

    player = Player(0, 'TerminusSTC', 100, 100, 'Slytherin', room, (12, 9))
    h_student = NPC(1, 'student', room, (12,12))

    # Setup curses
    curses.noecho()
    curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_BLACK)
    curses.init_pair(2, curses.COLOR_YELLOW, curses.COLOR_BLACK)
    curses.init_pair(3, curses.COLOR_RED, curses.COLOR_BLACK)
    curses.init_pair(4, curses.COLOR_GREEN, curses.COLOR_BLACK)
    curses.init_pair(5, curses.COLOR_BLUE, curses.COLOR_BLACK)

    log_strs = list()
    while True:
        input_box = renderMainView(window, room, player, log_strs)
        cmd_input = input_box.edit()

        log_strs.append(cmd_input)
        split_input = cmd_input.split()
        spell, spell_args = split_input[0], split_input[1:]
        player.castSpell(spell, spell_args=spell_args)

        time.sleep(1.0)
Exemple #2
0
    def __init__ (self):
        self.board = puzzle_2048()
        
        self.screen = curses.initscr()
        self.screen.keypad(1)
        self.screen.leaveok(0)
        curses.start_color()
        curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK)
        curses.noecho()
        curses.curs_set(0)
        
        self.screen.addstr(0,0,"To play: combine the tiles that match using the arrow keys, and press esc to exit")
        
        #Drawing the lines for the board
        self.screen.hline(5,10,"-", 29, curses.color_pair(1))
        self.screen.hline(9,10,"-", 29, curses.color_pair(1))
        self.screen.hline(13,10,"-", 29, curses.color_pair(1))
        self.screen.hline(17,10,"-", 29, curses.color_pair(1))
        self.screen.hline(21,10,"-", 29, curses.color_pair(1))
        self.screen.vline(5,10,"|", 17, curses.color_pair(1))
        self.screen.vline(5,17,"|", 17, curses.color_pair(1))
        self.screen.vline(5,24,"|", 17, curses.color_pair(1))
        self.screen.vline(5,31,"|", 17, curses.color_pair(1))
        self.screen.vline(5,38,"|", 17, curses.color_pair(1))
        
        self.Update_screen()

        self.run()
Exemple #3
0
 def init(self):
     self.window = curses.initscr()
     self.initted = True
     self.ymax, self.xmax = self.window.getmaxyx()
     terminfo = curses.longname()
     assert '256' in terminfo  # your env TERM must be xterm-256color!
     assert curses.has_colors()
     curses.start_color()
     curses.use_default_colors()
     ctr = 1
     for fg in CLRS:
         for bg in CLRS:
             if ctr <= curses.COLORS-1 and fg != bg:
                 curses.init_pair(ctr, CLRS[fg], CLRS[bg])
                 pairs[(fg,bg)] = curses.color_pair(ctr)
                 ctr += 1
     curses.meta(1)
     curses.noecho()
     curses.cbreak()
     curses.curs_set(0)
     curses.delay_output(0)
     curses.mouseinterval(150)
     availmask,_ = curses.mousemask(curses.ALL_MOUSE_EVENTS)
     assert availmask != 0  # mouse must be available!
     self.window.leaveok(1)
     self.window.scrollok(0)
     self.window.keypad(1)
     if NONBLOCKING:
         self.window.nodelay(1)
         self.window.timeout(NONBLOCKING_TIMEOUT)
     else:
         self.window.nodelay(0)
         self.window.timeout(-1)
     self.window.refresh()
def temperaturePrint(something):
    response = None
    temp_txt = ""
    rain_prob_txt = ""
    sunshine_length_txt = ""
    wind_txt = ""
    api = WetterQueryApi("12099", "16156188")
    try:
        response = api.call()
        temp_txt = response.temp + "C"
        rain_prob_txt = response.rain + "mm"
        sunshine_length_txt = response.sun + "h"
        wind_txt = response.wind + "km/h"
    except:
        None
    else:
        None 
    weather_txt = "sun: " + sunshine_length_txt + "  rain: " + rain_prob_txt + "  temp: " + temp_txt + "  wind: " + wind_txt
    terminalSize = os.popen('stty size', 'r').read().split()
    terminalHeight = int(terminalSize[0])  
    terminalWidth = int(terminalSize[1]) 
    curses.init_pair(1, curses.COLOR_YELLOW, curses.COLOR_BLACK)
    screen.addstr(terminalHeight-1,terminalWidth-len(weather_txt)-1,weather_txt, curses.color_pair(1))
    if type(something) == 'str':
        screen.addstr(terminalHeight-1,0, something)
    else:
        screen.addstr(terminalHeight-1,0,str(something))
    screen.refresh()
Exemple #5
0
    def drawscreen(self):
        self.dontupdate.acquire()
        # determine terminal width and height
        numlines, numcols = self.get_termsize()

        # define colors
        curses.init_pair(1, curses.COLOR_RED, curses.COLOR_WHITE)
        

        # render title bar
        tbtext = "pattirc v0.0"
        tbtext_padded = tbtext
        for i in range(numcols - len(tbtext)):
            tbtext_padded = tbtext_padded + " "
        self.screen.addstr(0, 0, tbtext_padded, curses.color_pair(1))
        self.screen.refresh()

        # render current buffer
        if len(self.buffers) > 0:
            currentbuffer = self.buffers[self.buffer_index]
            blankline = ""
            for i in range(numcols):
                blankline += " "
            self.screen.addstr(1,0, blankline)
            self.screen.addstr(1,0, currentbuffer.name)
            self.screen.addstr(2,0, currentbuffer.render(width=numcols,
                height=numlines-4))    

        self.dontupdate.release()
Exemple #6
0
    def init_and_run(self, stdscr):
        """ called by ncurses.wrapper """
        self.stdscr = stdscr

        try:
            curses.curs_set(0)
        except:
            pass

        curses.init_pair(1, curses.COLOR_CYAN, curses.COLOR_BLACK)
        curses.init_pair(2, curses.COLOR_WHITE, curses.COLOR_BLACK)
        curses.init_pair(3, curses.COLOR_GREEN, curses.COLOR_BLACK)
        curses.init_pair(4, curses.COLOR_YELLOW, curses.COLOR_BLACK)
        curses.init_pair(5, curses.COLOR_RED, curses.COLOR_BLACK)

        self.max_y, self.max_x = stdscr.getmaxyx()

        self.head_win = curses.newwin(4, self.max_x, 0, 0)
        self.body_win = curses.newwin(self.max_y-4, self.max_x, 4, 0)

        self.init_head_win()
        self.init_body_win()
        curses.doupdate()

        self.run()
  def __init__(self, settings, options, db, initial_filter):
    OpenDialogBase.__init__(self, settings, options, db, initial_filter)
    message_loop_curses.on_terminal_readable.add_listener(self._on_readable)
    self._stdscr = message_loop_curses.get_stdscr()

    self._refresh_pending = False
    self._invalidate()

    self._status = ''
    self._update_border()

    self._update_filter_text()

    h,w = self._stdscr.getmaxyx()
    self._stdscr.hline(1, 0, '-', w)
    self._stdscr.hline(h - 3, 0, '-', w)
    
    self._selected_index = 0
    self._result_files = []
    self._result_ranks = []

    # The location of the "cursor" in the filter text "readline" area
    if self.should_position_cursor_for_replace:
      self._filter_text_point = 0
    else:
      self._filter_text_point = len(self._filter_text)

    curses.init_pair(1, 1, curses.COLOR_BLACK)
Exemple #8
0
 def init(self):
     """init(self) -> None
     Colour initialization.
     """
     curses.start_color()
     for key, color in self._ColorSets.items():
         curses.init_pair( color['id'], color['pair'][0],  color['pair'][1] )
Exemple #9
0
    def __init__(self, evm):
        self.evm = evm
        evm.RegisterListener(self)
        # first we must create a window object; it will fill the whole screen
        self.scrn = curses.initscr()
        # turn off keystroke echo
        curses.noecho()
        # keystrokes are honored immediately, rather than waiting for the
        # user to hit Enter
        curses.cbreak()

        self.scrn.keypad(1)

        self.scrn.nodelay(1)
        # start color display (if it exists; could check with has_colors())
        curses.start_color()

        curses.mousemask(curses.BUTTON1_PRESSED)

        curses.curs_set(0)

        # clear screen
        self.scrn.clear()

        i = 1
        for color_background in self.list_of_colors:
            for color_foreground in self.list_of_colors:
                curses.init_pair(i, color_foreground, color_background)
                self.mapping[color_foreground, color_background] = i
                i += 1

        # implement the actions done so far (just the clear())
        self.scrn.refresh()
Exemple #10
0
    def setScreen(self, scr):
        """
		Set the screen and create the different windows 
		"""
        log(self.__class__.__name__, sys._getframe().f_code.co_name)
        self.stdscr = scr
        if self.stdscr != None:
            curses.curs_set(0)
            curses.start_color()
            curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_BLUE)
            curses.halfdelay(2 * 10)

            # setup all windows
            self.mainWindow = MainDisplay(0, self.stdscr)

            # self.stdscr.hline(self.WinPositions.headerBlock+self.headerWindow.getmaxyx()[0], 0, '-', 130)
            self.jobWindow = JobDisplay(0, self.stdscr)
            # self.stdscr.hline(self.WinPositions.summaryBlock+self.jobsWindow.getmaxyx()[0], 0, '-', 130)
            ##self.stdscr.hline(self.WinPositions.submitBlock+self.submitWindow.getmaxyx()[0], 0, '-', 130)

            ##self.erroWindow = curses.newwin(5, self.stdscr.getmaxyx()[1], self.WinPositions.debugBlock, 0)
            ##self.finalWindow = curses.newwin(3, self.stdscr.getmaxyx()[1], self.WinPositions.finalizeBlock, 0)
            ##self.finalWindow.addstr(0, 50, "Finalization job result")
            ##self.stdscr.hline(self.WinPositions.finalizeBlock+self.submitWindow.getmaxyx()[0], 0, '-', 130)
            ##
            ##self.stdscr.nooutrefresh()
            ##self.repaint()

            self.mainWindow.generate()
            self.jobWindow.generate()
            self.stdscr.refresh()
            self.activateMainWindow()
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()
Exemple #12
0
  def __init__(self):
    self.myscreen = curses.initscr()
    self.thread = None
    self.threadName = 'CLI'

    curses.noecho()
    curses.cbreak()
    curses.start_color()
    self.myscreen.keypad(1)

    curses.init_pair(1, curses.COLOR_BLACK, curses.COLOR_WHITE)
    self.myscreen_highlighted = curses.color_pair(1)
    self.myscreen_normal = curses.A_NORMAL

    self.menus = {
      'title': "Main Menu", 'type': MENU_TYPES.MENU, 'subtitle': "Select an option...", 'options': [
        { 'title': "Status", 'type': MENU_TYPES.MENU, 'subtitle': "Select an option..", 'options': [
          { 'title': "Media Information", 'type': MENU_TYPES.COMMAND, 'command': 'printMediaInfo' },
          { 'title': "Thread Information", 'type': MENU_TYPES.COMMAND, 'command': 'printThreadInfo' }
          ]
        }
      ]
    }

    self.commands = {
      'printMediaInfo': _printMediaInfo(),
      'printThreadInfo': _printThreadInfo()
    }

    self.initThread()
Exemple #13
0
    def __init__(self, stdscr, args):
        self._stdscr = stdscr
        self._dbase = database.load_file(args.database,
                                         encoding=args.encoding,
                                         frame_id_mask=args.frame_id_mask,
                                         strict=not args.no_strict)
        self._single_line = args.single_line
        self._filtered_sorted_message_names = []
        self._filter = ''
        self._compiled_filter = None
        self._formatted_messages = {}
        self._playing = True
        self._modified = True
        self._show_filter = False
        self._queue = Queue()
        self._nrows, self._ncols = stdscr.getmaxyx()
        self._received = 0
        self._discarded = 0
        self._basetime = None

        stdscr.nodelay(True)
        curses.use_default_colors()
        curses.curs_set(False)
        curses.init_pair(1, curses.COLOR_BLACK, curses.COLOR_GREEN)
        curses.init_pair(2, curses.COLOR_BLACK, curses.COLOR_CYAN)

        bus = self.create_bus(args)
        self._notifier = can.Notifier(bus, [self])
Exemple #14
0
    def start(self):
        """Initialize curses. Mostly copied from curses/wrapper.py"""

        # This might do some good
        locale.setlocale(locale.LC_ALL, "")

        # Initialize curses
        stdscr = curses.initscr()

        # Turn off echoing of keys, and enter cbreak mode,
        # where no buffering is performed on keyboard input
        curses.noecho()
        curses.cbreak()

        # In keypad mode, escape sequences for special keys
        # (like the cursor keys) will be interpreted and
        # a special value like curses.KEY_LEFT will be returned
        stdscr.keypad(1)

        # Start color, too.  Harmless if the terminal doesn't have
        # color; user can test with has_color() later on.  The try/catch
        # works around a minor bit of over-conscientiousness in the curses
        # module -- the error return from C start_color() is ignorable.
        try:
            curses.start_color()
            curses.use_default_colors()
            for i in range(1, curses.COLORS):
                curses.init_pair(i, i, -1)
        except:
            LOG.exception("Exception in curses color init")

        self.stdscr = stdscr
Exemple #15
0
def main(scr):
    curses.curs_set(False)

    curses.start_color()
    for i in range(1, 16):
        curses.init_pair(i, i, curses.COLOR_BLACK)

    scry, scrx = scr.getmaxyx()
    pady = scry * 2
    padx = scrx * 2

    pad = curses.newpad(pady, padx)
    pad.nodelay(True)
    mandel(pad)

    oy = 1
    ox = 0

    while True:
        pad.refresh(oy, ox, 0, 0, scry-1, scrx-1)
        key = pad.getch()
        if key in (ord('q'), ord('Q')):
            break
        elif key in (ord('w'), curses.KEY_UP):
            oy = max(oy - 1, 0)
        elif key in (ord('s'), curses.KEY_DOWN):
            oy = min(oy + 1, pady - scry - 1)
        elif key in (ord('a'), curses.KEY_LEFT):
            ox = max(ox - 2, 0)
        elif key in (ord('d'), curses.KEY_RIGHT):
            ox = min(ox + 2, padx - scrx)
        elif key == curses.KEY_RESIZE:
            scry, scrx = scr.getmaxyx()
Exemple #16
0
def main(stdscr):
    curses.start_color()
    curses.use_default_colors()

    for bg in range(256):
        for i in range(0, curses.COLORS):
            curses.init_pair(i + 1, i, bg)
        try:
            for i in range(256):
                # c = str(i)
                c = curses.ACS_ULCORNER
                c = ord('a')
                c = u'\u239e'
                c = u'\u2588'
                # c = 9608
                # c = u'\u239e'.encode("utf-8")
                # c = u'\u0438'.encode('utf-8')
                stdscr.addstr(c, curses.color_pair(i))
                # stdscr.addch(9118)
                # stdscr.addstr('\\u239e')
                # stdscr.addch(c)
                if i < 16:
                    stdscr.addstr(' ', curses.color_pair(i))
                if i in (16,52,88,124,160,196,232,):
                    stdscr.addstr('\n', curses.color_pair(i))
            stdscr.addstr('\n', curses.color_pair(i))
        except curses.error:
            # End of screen reached
            pass
        if stdscr.getch() == ord('q'):
            break
        stdscr.clear()
Exemple #17
0
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, "â–ˆ")
Exemple #18
0
    def choose_agent(window):
        agents = registry.get_names()
        curses.init_pair(3, curses.COLOR_WHITE, curses.COLOR_BLUE)
        window.addstr(10, 34, "Choose agent---SEER DIMENSIONS WAR")
        ch = 0
        selected = 0
        while ch != 10 and ch != 27:
            index = 0
            for agent in agents:
                if index == selected:
                    color = curses.color_pair(3)
                else:
                    color = curses.color_pair(0)
                window.addstr(index + 11, 25, "{:^30}".format(agent), color)
                index += 1

            window.refresh()
            ch = window.getch()
            if ch == curses.KEY_UP:
                selected -= 1
                if selected < 0:
                    selected = len(agents) - 1
            if ch == curses.KEY_DOWN:
                selected += 1
                if selected == len(agents):
                    selected = 0

        window.clear()
        if ch == 27:
            sys.exit(0)
        else:
            return registry.create_agent(agents[selected])
Exemple #19
0
    def __init__(self, wallet, config, app=None):
        self.stdscr = curses.initscr()
        curses.noecho()
        curses.cbreak()
        curses.start_color()
        curses.use_default_colors()
        curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_BLUE)
        curses.init_pair(2, curses.COLOR_WHITE, curses.COLOR_CYAN)
        self.stdscr.keypad(1)
        self.stdscr.border(0)
        self.maxy, self.maxx = self.stdscr.getmaxyx()
        curses.curs_set(0)
        self.w = curses.newwin(10, 50, 5, 5)

        self.wallet = wallet
        self.config = config
        set_verbosity(False)
        self.tab = 0
        self.pos = 0
        self.popup_pos = 0

        self.str_recipient = ""
        self.str_description = ""
        self.str_amount = ""
        self.str_fee = ""
        
        self.wallet.interface.register_callback('updated', self.refresh)
        self.wallet.interface.register_callback('connected', self.refresh)
        self.wallet.interface.register_callback('disconnected', self.refresh)
        self.wallet.interface.register_callback('disconnecting', self.refresh)
        self.tab_names = [_("History"), _("Send"), _("Receive"), _("Contacts"), _("Wall")]
        self.num_tabs = len(self.tab_names)
Exemple #20
0
    def main(stdscr):
        try:
            curses.use_default_colors()
            curses.init_pair(1, -1, curses.COLOR_CYAN)
            curses.init_pair(2, -1, curses.COLOR_BLUE)
        except:
            pass

        # add some numbers to background so we can see window
        for y in range(0, curses.LINES - 1):
            for x in range(0, curses.COLS):
                stdscr.addstr("%d" % ((y + x) % 10))
        stdscr.addstr(curses.LINES - 1, 0, "Press tab to quit.")
        stdscr.refresh()

        win = stdscr.subwin(22,50,5,5)
        win.bkgdset(ord(' '), curses.color_pair(1))
        win.clear()
        win.border()
        win.addstr(0, 2, "[ Window with an embedded ListBox ]")
        win.addstr(2, 3, "Select an item then press tab to")
        win.addstr(3, 3, "send selection to parent.")

        # generate list of test data
        data = map(lambda x: chr(x)+'_test'+str(x), range(ord('a'),ord('z')))

        lb = ListBox(win, 15, 30, 5, 5, data, 2)
        selection = lb.focus()

        win.erase()

        stdscr.clear()

        stdscr.addstr(10,10, "Selected item: %s" % selection)
        stdscr.getch()
Exemple #21
0
	def setupCurses(self):

		self.titlewin = self.stdscr.subwin(1, 80, 0, 0)
		self.mainwin = self.stdscr.subwin(23, 80, 1, 0)
		self.progwin = self.stdscr.subwin(10, 60, 6, 10)
		self.statwin = self.stdscr.subwin(1, 80, 24, 0)

		self.progBar = progressBar(0, 100, 56)

		curses.init_pair(1, curses.COLOR_BLACK, curses.COLOR_WHITE)
		curses.init_pair(2, curses.COLOR_WHITE, curses.COLOR_CYAN)
		curses.init_pair(3, curses.COLOR_YELLOW, curses.COLOR_WHITE)
		curses.init_pair(4, curses.COLOR_RED, curses.COLOR_WHITE)
		curses.init_pair(5, curses.COLOR_WHITE, curses.COLOR_BLACK)

		self.titlewin.bkgd(' ', curses.color_pair(1))
		self.statwin.bkgd(' ', curses.color_pair(1))
		self.mainwin.bkgd(' ', curses.color_pair(2))

		self.titlewin.addstr(0, 0, "Installing " + self.packageName)
		self.statwin.addstr(0, 0, "Please wait...")

		self.resetProgWin()

		self.stdscr.refresh()
Exemple #22
0
    def main(stdscr):
        try:
            curses.use_default_colors()
            curses.init_pair(1, -1, curses.COLOR_CYAN)
            curses.init_pair(2, -1, curses.COLOR_BLUE)
        except:
            pass

        # add some numbers to background so we can see window
        for y in range(0, curses.LINES - 1):
            for x in range(0, curses.COLS):
                stdscr.addstr("%d" % ((y + x) % 10))
        stdscr.addstr(curses.LINES - 1, 0, "Press tab to select.")
        stdscr.refresh()

        win = stdscr.subwin(22,50,5,5)
        win.bkgdset(ord(' '), curses.color_pair(1))
        win.clear()
        win.border()
        win.addstr(0, 2, "[ Window with an embedded Button ]")

        button1 = Button(win, 4, 4, "Quit")
        button2 = Button(win, 6, 4, "Stay")

        while 1:
            if button1.focus():
                break
            button2.focus()
Exemple #23
0
	def init(self):
		self.screen = curses.initscr()
		curses.noecho()
		curses.cbreak()
		self.screen.keypad(1)

		try:
			curses.curs_set(0)
		except:
			logging.warning("Cursor hiding is not supported")

		curses.halfdelay(1) # block for 0.1s

		if curses.has_colors():
			self.colors = True
			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.init_pair(4, curses.COLOR_YELLOW, curses.COLOR_BLACK)
			curses.init_pair(5, curses.COLOR_BLUE, curses.COLOR_BLACK)
		else:
			self.colors = False
			logging.warning("Colors are not supported")

		logging.info("Console I/O initialized")
Exemple #24
0
	def init_curses(self):
		"""
		This initializes the screen for curses useage.  It must be
		called before Curses can be used.
		"""
		self.user_marker_pos = 1  # Used with curses
		self.curses_row_offset = 0  # Used for marking the visible rows on the screen to allow scrolling
		self.curses_row_offset_store = 0  # Used for storing the row offset when switching from detailed to non-detailed view modes
		self.curses_detailed = None  # Used with curses
		self.screen = curses.initscr()
		curses.start_color()
		curses.init_pair(1, curses.COLOR_BLUE, curses.COLOR_WHITE)
		size = self.screen.getmaxyx()
		if size[0] < CURSES_MIN_Y or size[1] < CURSES_MIN_X:
			curses.endwin()
			return 1
		self.curses_max_rows = size[0] - 2  # Minus 2 for the border on the top and bottom
		self.curses_max_columns = size[1] - 2

		self.screen.border(0)
		self.screen.addstr(2, TAB_LENGTH, 'EAPeak Capturing Live')
		self.screen.addstr(3, TAB_LENGTH, 'Found 0 Networks')
		self.screen.addstr(4, TAB_LENGTH, 'Processed 0 Packets')
		self.screen.addstr(self.user_marker_pos + USER_MARKER_OFFSET, TAB_LENGTH, USER_MARKER)
		self.screen.refresh()
		try:
			curses.curs_set(1)
			curses.curs_set(0)
		except curses.error:  # Ignore exceptions from terminals that don't support setting the cursor's visibility
			pass
		curses.noecho()
		curses.cbreak()
		self.curses_enabled = True
		self.curses_lower_refresh_counter = 1
		return 0
def make_panel(h,l, y,x, str): 
	curses.init_pair(1, curses.COLOR_RED, curses.COLOR_BLACK)

	win = curses.newwin(h,l, y,x) 
	win.erase() 
	panel = curses.panel.new_panel(win) 
	return win, panel 
Exemple #26
0
    def cursesGameLoop(self, scr):
        curses.start_color()

        if self.config["use-default-colors"]:
            curses.use_default_colors()
            bg = -1
        else:
            bg = curses.COLOR_BLACK

        for c in xrange(8):
            curses.init_pair(c + 1, c, bg)

        curses.curs_set(0)
        mainwin = scr
        win = mainwin
        #win = curses.newwin(30, 100, 10, 10)
        win.nodelay(True)

        game = self.activity

        while True:
            game.clock.time = time.time() * 1000
            game.update()
            
            if game.paused:
                game.resume()

            game.renderer.draw(win)
Exemple #27
0
def get_color(fg, bg):
    """Returns the curses color pair for the given fg/bg combination."""

    key = (fg, bg)
    if key not in COLOR_PAIRS:
        size = len(COLOR_PAIRS)
        try:
            curses.init_pair(size, fg, bg)
        except curses.error:
            # If curses.use_default_colors() failed during the initialization
            # of curses, then using -1 as fg or bg will fail as well, which
            # we need to handle with fallback-defaults:
            if fg == -1:  # -1 is the "default" color
                fg = DEFAULT_FOREGROUND
            if bg == -1:  # -1 is the "default" color
                bg = DEFAULT_BACKGROUND

            try:
                curses.init_pair(size, fg, bg)
            except curses.error:
                # If this fails too, colors are probably not supported
                pass
        COLOR_PAIRS[key] = size

    return COLOR_PAIRS[key]
Exemple #28
0
def _color_attr():
  """
  Initializes color mappings usable by curses. This can only be done after
  calling curses.initscr().
  """

  global COLOR_ATTR

  if COLOR_ATTR is None:
    if not CONFIG['features.colorInterface']:
      COLOR_ATTR = DEFAULT_COLOR_ATTR
    elif curses.has_colors():
      color_attr = dict(DEFAULT_COLOR_ATTR)

      for color_pair, color_name in enumerate(COLOR_LIST):
        foreground_color = COLOR_LIST[color_name]
        background_color = -1  # allows for default (possibly transparent) background
        curses.init_pair(color_pair + 1, foreground_color, background_color)
        color_attr[color_name] = curses.color_pair(color_pair + 1)

      log.info('setup.color_support_available')
      COLOR_ATTR = color_attr
    else:
      log.info('setup.color_support_unavailable')
      COLOR_ATTR = DEFAULT_COLOR_ATTR

  return COLOR_ATTR
Exemple #29
0
    def __init__(self, game, term_width, term_height,stdscr): 
        self.game = game
        self.stdscr = stdscr
        
        """
        break up the screen into four panes:
        ----------------
        | a     |b     |
        |       |      |
        |-------|      |
        | c     |      |
        ----------------
        | d            |
        ----------------
        window a is for drawing the hangman
        window b is for recording the guesses
        window c is for showing the word (blanks and correct letters)
        window d is for communicating with the user
        """
        self.a = curses.newwin(int(term_height*4/6), int(term_width/2), 0,0) 
        self.b = curses.newwin(int(term_height*4/6), int(term_width/2), 
                                0, int(term_width/2)) 
        self.c = curses.newwin(int(term_height*1/6), term_width,
                                int(term_height*4/6), 0) 
        self.d = curses.newwin(int(term_height*1/6), term_width,
                                int(term_height*5/6), 0)

        #initialize magenta colour pairing for printing out guessed letters.
        curses.init_pair(1, curses.COLOR_MAGENTA,curses.COLOR_BLACK)
Exemple #30
0
 def initPairs(self):
     """THIS DOESN'T NEED TO BE A METHOD!!"""
     curses.init_pair(1, 1, curses.COLOR_BLACK)
     curses.init_pair(2, 2, curses.COLOR_BLACK)
     curses.init_pair(3, 3, curses.COLOR_BLACK)
     curses.init_pair(4, 4, curses.COLOR_BLACK)
     curses.init_pair(5, 5, curses.COLOR_BLACK)
Exemple #31
0
    # the lenght of pad (since stdscr and stdpad will have the same width
    # we can use stdscr to comute its lenght)
    # XXX: without +1: last line is repeated till the end of stdscr. Why?
    stdpad = curses.newpad(ypad, x_stdscr)
    (ytop, xtop) = (0, 0)  # stdpad
    curses.start_color()
    curses.use_default_colors()
    # use this for transparency (then -1 can be used as the default background
    # color)
    curses.noecho()  # turn off automatic echoing of keys to the screen
    curses.cbreak()  # react to keays instantly (without requireing Enter)
    stdscr.keypad(1)
    curses.curs_set(0)
    curses.meta(1)

    curses.init_pair(0, -1, -1)
    # no hightlight
    curses.init_pair(1, curses.COLOR_RED, -1)
    # it is used when the author matches a pattern.
    # also used to hightligh that the entry is in the sqlite3 database
    # also to hightlight the title in the detailed view.
    curses.init_pair(2, curses.COLOR_GREEN, -1)
    # it is used when the title or abstract matches a pattern.
    # also used to highlight numbers of entries on the left
    curses.init_pair(3, curses.COLOR_RED, -1)
    curses.init_pair(4, curses.COLOR_WHITE, curses.COLOR_BLUE)
    curses.init_pair(5, curses.COLOR_WHITE, curses.COLOR_GREEN)

    def clear_status():
        """
        Clear the status line.
Exemple #32
0
def view_colormap(stdscr, cmap=None, num=True):
    curses.use_default_colors()

    from inspec.colormap import curses_cmap, load_cmap

    if cmap is None:
        show_full = True
    else:
        show_full = False

    WIDTH = 4
    if show_full:
        # might have a different behavior on windows vs ubuntu
        i = 1
        for color in range(255):
            curses.init_pair(i, color + 1, -1)
            i += 1

        blocks = [
            range(0, 16),
            range(16, 16 + 36),
            range(16 + 36, 16 + 72),
            range(16 + 72, 16 + 108),
            range(16 + 108, 16 + 144),
            range(160, 160 + 36),
            range(160 + 36, 160 + 72),
            range(160 + 72, 256),
        ]
        tempts = []
        for i, block in enumerate(blocks):
            if i == 0 or i == 7:
                for block_idx, color_idx in enumerate(block):
                    color_str = str(color_idx)
                    if num:
                        full_str = (WIDTH - len(color_str)) * " " + color_str
                    else:
                        full_str = WIDTH * const.FULL_1

                    col = ((i) // 2) * WIDTH * 6
                    row = block_idx
                    color = curses.color_pair(color_idx)
                    tempts.append((row, col))
                    try:
                        stdscr.addstr(row, col, full_str, color)
                    except curses.error:
                        continue
            else:
                bottom = bool(i % 2 == 0)
                for block_idx, color_idx in enumerate(block):
                    color_str = str(color_idx)
                    if num:
                        full_str = (WIDTH - len(color_str)) * " " + color_str
                    else:
                        full_str = WIDTH * const.FULL_1

                    row = bottom * 6 + block_idx % 6
                    col = WIDTH + (
                        (i - 1) // 2) * WIDTH * 6 + (block_idx // 6) * WIDTH
                    color = curses.color_pair(color_idx)
                    stdscr.addstr(row, col, full_str, color)
    else:
        cmap = load_cmap(cmap)
        curses_cmap.init_colormap(cmap)

        col_idx = 0
        row_idx = 0
        for color0 in curses_cmap.colors:
            for color1 in curses_cmap.colors:
                slot, inv = curses_cmap.get_slot(color0, color1)
                color_str = str(slot)
                if num:
                    full_str = (WIDTH - len(color_str)) * " " + color_str
                else:
                    if color0.idx == color1.idx == 0:
                        full_str = WIDTH * const.FULL_0
                    elif color0.idx == color1.idx != 0:
                        full_str = WIDTH * const.FULL_1
                    elif inv:
                        full_str = WIDTH * const.QTR_1001
                    else:
                        full_str = WIDTH * const.QTR_0110
                row_idx += 1
                color = curses.color_pair(slot)
                try:
                    stdscr.addstr(row_idx, col_idx, full_str, color)
                except curses.error:
                    pass
            col_idx += WIDTH
            row_idx = 0
    while True:
        ch = stdscr.getch()
        if ch == ord("q"):
            break
Exemple #33
0
 def init_colors():
     """ Init curses colors """
     curses.start_color()
     curses.use_default_colors()
     for i in range(0, 255):
         curses.init_pair(i + 1, i, -1)
Exemple #34
0
def setup_colors():
    # start and setup colors
    curses.start_color()
    curses.init_pair(1, curses.COLOR_CYAN, curses.COLOR_BLACK)
    curses.init_pair(2, 3, curses.COLOR_BLACK)
    curses.init_pair(3, curses.COLOR_WHITE, curses.COLOR_BLACK)
    curses.init_pair(4, 6, curses.COLOR_BLACK)
    curses.init_pair(5, 8, curses.COLOR_BLACK)
    curses.init_pair(6, 9, curses.COLOR_BLACK)
    curses.init_pair(7, curses.COLOR_RED, curses.COLOR_BLACK)
    curses.init_pair(8, curses.COLOR_GREEN, curses.COLOR_BLACK)
    curses.init_pair(9, curses.COLOR_BLUE, curses.COLOR_BLACK)
Exemple #35
0
def display_access_points(information, mac_matcher):
    """
    Display information in the box window

    :param information: (screen, box, access_points, total_ap_number, page_number, position)
    :type information: tuple
    :return: None
    :rtype: None
    .. note: The display system is setup like the following:

             ----------------------------------------
             - (1,3)Options                         -
             -   (3,5)Header                        -
             - (4,3)****************************    -
             -      *       ^                  *    -
             -      *       |                  *    -
             -      *       |                  *    -
             -    < *       |----              *    -
             -    v *       |   v              *    -
             -    v *       |   v              *    -
             -    v *       |   v              *    -
             -    v *       v   v              *    -
             -    v ************v***************    -
             -    v             v      v            -
             -----v-------------v------v-------------
                  v             v      v
                  v             v      > max_window_length-5
                  v             v
            max_window_height-9 v
                                V
                                v--> box_height-2

    """

    # setup the font color
    curses.init_pair(1, curses.COLOR_BLACK, curses.COLOR_CYAN)
    highlight_text = curses.color_pair(1)
    normal_text = curses.A_NORMAL

    # extract all the required information
    screen = information[0]
    box = information[1]
    access_points = information[2]
    total_ap_number = information[3]
    page_number = information[4]
    position = information[5]
    # TODO: pass max_row so you don't have to calculate it again
    # calculate the box's maximum number of row's
    box_height = box.getmaxyx()[0]
    # subtracting 2 from the height for the border
    max_row = box_height - 2

    # get the page boundary
    page_boundary = range(1 + (max_row * (page_number - 1)),
                          max_row + 1 + (max_row * (page_number - 1)))

    # remove previous content and draw border
    box.erase()
    box.border(0)

    # show the header
    header = ("{0:30} {1:17} {2:2} {3:3} {4:7} {5:20}".format(
        "ESSID", "BSSID", "CH", "PWR", "CLIENTS", "VENDOR"))
    screen.addstr(
        1, 3,
        "Options:  [Esc] Quit  [Up Arrow] Move Up  [Down Arrow] Move Down")
    screen.addstr(3, 5, header)

    # show all the items based on their position
    for item_position in page_boundary:
        # in case of no access points discovered yet
        if total_ap_number == 0:
            box.addstr(1, 1, "No access point has been discovered yet!",
                       highlight_text)

        # in case of at least one access point
        else:
            # get the access point and it's vendor
            access_point = access_points[item_position - 1]
            vendor = mac_matcher.get_vendor_name(
                access_point.get_mac_address())

            # the display format for showing access points
            display_text = ("{0:30} {1:17} {2:2} {3:3}% {4:^7} {5:20}".format(
                access_point.get_name(), access_point.get_mac_address(),
                access_point.get_channel(), access_point.get_signal_strength(),
                access_point.get_number_connected_clients(), vendor))

            # shows whether the access point should be highlighted or not
            # based on our current position
            if item_position + (max_row * (page_number - 1)) == position + (
                    max_row * (page_number - 1)):
                box.addstr(item_position - (max_row * (page_number - 1)), 2,
                           display_text, highlight_text)
            else:
                box.addstr(item_position - (max_row * (page_number - 1)), 2,
                           display_text, normal_text)

            # stop if it is the last item in page
            if item_position == total_ap_number:
                break

    # update the screen
    screen.refresh()
    box.refresh()
Exemple #36
0
 def setup_screen(self, input_file):
     """
     Sets up the curses terminal with the appropriate colour scheme.
     """
     curses.init_color(curses.COLOR_MAGENTA, 999, 0, 600)
     curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK)
     curses.init_pair(2, curses.COLOR_RED, curses.COLOR_BLACK)
     curses.init_pair(3, curses.COLOR_BLUE, curses.COLOR_BLACK)
     curses.init_pair(4, curses.COLOR_WHITE, curses.COLOR_BLACK)
     curses.init_pair(5, curses.COLOR_YELLOW, curses.COLOR_BLACK)
     curses.init_pair(6, curses.COLOR_CYAN, curses.COLOR_BLACK)
     curses.init_pair(7, curses.COLOR_MAGENTA, curses.COLOR_BLACK)
     self.stdscr.addstr(0, 100, "REGISTER FILE", curses.A_BOLD)
     self.stdscr.addstr(0, 10, "MACHINE INFORMATION", curses.A_BOLD)
     self.stdscr.addstr(2, 10, "Program: " + str(input_file), curses.color_pair(4))
     self.stdscr.addstr(4, 35, "Cycles per second: " + str(1 / instruction_time)[:5], curses.color_pair(3))
     self.stdscr.addstr(12, 10, "PIPELINE INFORMATION", curses.A_BOLD)
     self.stdscr.addstr(51, 0, "Press `SPACE' to automate execution or any other key to single step.")
Exemple #37
0
                    stdscr.addch(y, x, obj.ch_number,
                                 curses.color_pair(obj.color))
                except AttributeError:
                    stdscr.addstr(y, x, obj)
                except TypeError:
                    stdscr.addstr(y, x, obj.drawing,
                                  curses.color_pair(obj.color))
                stdscr.refresh()
                sleep(animation_speed)

            sleep(5)
            stdscr.clear()

    try:
        s = curses.initscr()
        curses.start_color()
        curses.use_default_colors()
        for i in range(0, curses.COLORS):
            curses.init_pair(i + 1, i, -1)
        main(s)
    finally:
        try:
            curses.nocbreak()
        except curses.error:
            import sys
            sys.exit()

        s.keypad(False)
        curses.echo()
        curses.endwin()
Exemple #38
0
def display(battery=None):  #print watchdog countdown
    global stdscr
    # Read ADC values
    adc_values = ADC.read()
    global frequency
    frequency = PLL.Get_Frequency()

    stdscr.addstr(0, 10, "Battery")
    stdscr.addstr(1, 0, "==============================")
    stdscr.addstr(2, 0, f"ADC:")
    stdscr.addstr(2, 10, f"Low Precision: {adc_values[0][0]}")
    stdscr.addstr(3, 10, f"High Precision: {adc_values[0][1]}")
    # Read Current values
    stdscr.addstr(4, 0, f"Current:")
    stdscr.addstr(4, 10, f"{adc_values[1]} A ")
    #Read CAN data
    CANdata = CAN.Get_CAN_Info()
    text = ' '.join(
        CANdata)  #put elements of the list of CAN data bytes into a string
    CANbox.erase()  #clear previous data in the box
    CANbox.addstr(4, 0, textwrap.fill(text, 40))
    CANbox.addstr(3, 2, "CAN ID and Message:")
    # Display Watchdog ticks
    ticks = WDTimer.Tick()
    stdscr.addstr(10, 0,
                  f"                              ")  #clear previous tick
    stdscr.addstr(10, 0, f"WDTimer Countdown: {ticks}")
    #Display current frequency
    stdscr.addstr(6, 0, f"                                          ")
    stdscr.addstr(6, 0, f"Clock Frequency: {frequency} Hz")
    # Read Module values
    stdscr.addstr(0, 54, "Modules")
    stdscr.addstr(1, 40, "====================================")
    module_values = SPI.read()
    for i, module in enumerate(module_values):
        stdscr.addstr(i + 2, 37, f"{i+1}")
        stdscr.addstr(
            i + 2, 40,
            f"| {'X' if module[0] else ' '} | {module[1]/10000:.4f}V | {module[2]/1000:.3f}°C | {module[3]/1000:.3f}°C | {module[4]}"
        )
    # Read LED values
    stdscr.addstr(0, 90, "LEDs")
    stdscr.addstr(1, 80, "=======================")
    lights = Lights.read()
    curses.init_pair(1, curses.COLOR_RED, curses.COLOR_RED)
    curses.init_pair(2, curses.COLOR_GREEN, curses.COLOR_GREEN)
    curses.init_pair(3, curses.COLOR_BLACK, curses.COLOR_BLACK)
    for i in range(9):
        stdscr.addstr(i + 2, 80, lights_names[i])
        if lights & (0x1 << i):
            if i == 7:
                stdscr.addstr(i + 2, 100, "[]", curses.color_pair(2))
            else:
                stdscr.addstr(i + 2, 100, "[]", curses.color_pair(1))
        else:
            stdscr.addstr(i + 2, 100, "[]", curses.color_pair(3))
    strobe = Strobelight.read()

    stdscr.addstr(11, 80, 'S_PULSING')
    if strobe:
        stdscr.addstr(11, 100, "[]", curses.color_pair(2))
    else:
        stdscr.addstr(11, 100, "[]", curses.color_pair(3))
    speed = Fans.read()
    stdscr.addstr(12, 9, "Fan Speeds")
    stdscr.addstr(13, 0, "================================")
    stdscr.addstr(14, 0, f"Fan 1: {speed[0]}/8")
    stdscr.addstr(14, 15, f"Fan 2: {speed[1]}/8")
    stdscr.addstr(15, 0, f"Fan 3: {speed[2]}/8")
    stdscr.addstr(15, 15, f"Fan 4: {speed[3]}/8")
    stdscr.refresh()
Exemple #39
0
    a = system(cmd_string)
    print("")
    if a == 0:
        print("Command executed correctly")
    else:
        print("Command terminated with error")
    input("Press enter")
    print("")


stdscr = curses.initscr()
curses.start_color()

x = 0
while x != ord('4'):
    screen = curses.initscr()
    screen.clear()
    screen.border(0)
    curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_BLUE)
    stdscr.addstr(0, 0, "RED ALERT!", curses.color_pair(1))
    screen.addstr(2, 2, "Please enter a number...")
    screen.addstr(4, 4, "1 - Add a user")
    screen.addstr(5, 4, "2 - Restart Apache")
    screen.addstr(6, 4, "3 - Show disk space")
    screen.addstr(7, 4, "4 - Exit")
    screen.refresh()

    x = screen.getch()

curses.endwin()
Exemple #40
0
def set_colors():
    if curses.can_change_color():
        # Light
        curses.init_color(COLOR_LIGHT, 240, 217, 181)
        # Dark
        curses.init_color(COLOR_DARK, 181, 136, 99)
        # White on light
        curses.init_pair(WHITE_ON_LIGHT, curses.COLOR_WHITE, COLOR_LIGHT)
        # White on dark
        curses.init_pair(WHITE_ON_DARK, curses.COLOR_WHITE, COLOR_DARK)
        # Black on light
        curses.init_pair(BLACK_ON_LIGHT, curses.COLOR_BLACK, COLOR_LIGHT)
        # Black on dark
        curses.init_pair(BLACK_ON_DARK, curses.COLOR_BLACK, COLOR_DARK)
    else:
        # White on light
        curses.init_pair(WHITE_ON_LIGHT, curses.COLOR_WHITE,
                         curses.COLOR_YELLOW)
        # White on dark
        curses.init_pair(WHITE_ON_DARK, curses.COLOR_WHITE, curses.COLOR_GREEN)
        # Black on light
        curses.init_pair(BLACK_ON_LIGHT, curses.COLOR_BLACK,
                         curses.COLOR_YELLOW)
        # Black on dark
        curses.init_pair(BLACK_ON_DARK, curses.COLOR_BLACK, curses.COLOR_GREEN)
Exemple #41
0
        option = 0 if option == len(options) - 1 else option + 1
    return option


def move_arrow(direction, screen):
    global current_option
    current_option = change_option(current_option, direction)
    screen.addstr(current_option, 0, "--> ", curses.color_pair(1))


stdscr = curses.initscr()
curses.cbreak()
curses.noecho()
curses.start_color()
curses.use_default_colors()
curses.init_pair(1, curses.COLOR_RED, -1)
curses.init_pair(2, curses.COLOR_BLUE, -1)
stdscr.keypad(1)
stdscr.refresh()

key = ''
while key != ord('q'):
    if key == curses.KEY_RIGHT and os.path.isdir(os.getcwd() + '/' +
                                                 options[current_option]):
        os.chdir(os.getcwd() + '/' + options[current_option])
        current_option = 0
    elif key == curses.KEY_LEFT:
        os.chdir('..')
        current_option = 0

    options = get_files()
Exemple #42
0
def start_experiment(stdscr, agent_to_examine):
    NODELAY = 0
    # grid definitions
    X_BOUND = 4  #length

    def in_bounds(pos):
        return (pos >= 0 and pos <= X_BOUND)

    # distance function
    def dist(p, q):
        return abs(p - q)

    # agent discount parameters
    MOTION_PARAMS = tuple([1. - pow(2, -6)])
    #ARBITRATION_PARAMS=tuple([1.-pow(2,-2)])
    #ARBITRATION_PEAK=2

    # initialize a new experiment
    EX = Experiment()
    id_dec = EX.nid('decision')

    # register basic motion agents;
    # - $True$ tag means they will be marked as dependent (on other agents)
    id_rt, id_rtc = EX.register_sensor('rt', True)
    id_lt, id_ltc = EX.register_sensor('lt', True)
    # register motivation for motion agents
    # - this one is NOT dependent on agents except through the position, so
    #   it carries the default False tag.
    id_distM = EX.register('distM')
    id_navM, cid_navM = EX.register_sensor('navM')
    # register supervising agent
    #id_super,id_superc=EX.register_sensor('super',True)

    # agent to be visualized
    id_lookat = EX.nid(agent_to_examine)

    # register arbiter variable whose purpose is to synchronize the responses
    # of agents 'lt' and 'rt' to the action of 'super', it does not depend on
    # agent decisions, hence carries the default False tag.
    id_arbiter = EX.register('ar', True)
    # register the failure mode sensor
    #id_fail,id_failc=EX.register_sensor('fl')

    # add a counter
    id_count = EX.register('count')

    def ex_counter(state):
        return 1 + state[id_count][0]

    EX.construct_measurable(id_count, ex_counter, [0])

    # introduce arbitration
    def arbiter(state):
        return bool(rnd(2))

    EX.construct_measurable(id_arbiter, arbiter, [bool(rnd(2))], 0)

    id_toRT, id_toRTc = EX.register_sensor('toR', True)

    def intention_RT(state):
        return id_rt in state[id_dec][0]

    EX.construct_sensor(id_toRT, intention_RT)

    id_toLT, id_toLTc = EX.register_sensor('toL', True)

    def intention_LT(state):
        return id_lt in state[id_dec][0]

    EX.construct_sensor(id_toLT, intention_LT)

    # failure mode for action $lt^rt$
    id_toF, id_toFc = EX.register_sensor('toF', True)

    def about_to_enter_failure_mode(state):
        return state[id_toLT][0] and state[id_toRT][0]

    EX.construct_sensor(id_toF, about_to_enter_failure_mode)

    # add basic motion agents
    def action_RT(state):
        rt_decided = (id_rt in state[id_dec][0])
        if state[id_toF][0]:
            #return not(rt_decided) if state[id_arbiter][0] else rt_decided
            return state[id_arbiter][0]
        else:
            return rt_decided

    RT = EX.construct_agent(id_rt, id_distM, action_RT, MOTION_PARAMS, True)

    def action_LT(state):
        lt_decided = (id_lt in state[id_dec][0])
        if state[id_toF][0]:
            #return lt_decided if state[id_arbiter][0] else not(lt_decided)
            return not (state[id_arbiter][0])
        else:
            return lt_decided

    LT = EX.construct_agent(id_lt, id_distM, action_LT, MOTION_PARAMS, True)

    # immediately introduce corresponding action sensors
    #EX.assign_sensor(id_rt,True,[id_lt])
    #EX.assign_sensor(id_lt,True,[id_rt])

    #
    ### "mapping" system
    #

    ## introduce agent's position

    # select starting position
    START = rnd(X_BOUND + 1)

    # effect of motion on position
    id_pos = EX.register('pos')

    def motion(state):
        triggers = {id_rt: 1, id_lt: -1}
        diff = 0
        for t in triggers:
            diff += triggers[t] * int(state[t][0])
        newpos = state[id_pos][0] + diff
        if in_bounds(newpos):
            return newpos
        else:
            return state[id_pos][0]

    EX.construct_measurable(id_pos, motion, [START, START])

    ## introduce effect of agent (not/)feeding (finding and consuming targets):

    # generate target position
    TARGET = START
    while dist(TARGET, START) < X_BOUND / 8:
        TARGET = rnd(X_BOUND + 1)

    # set up position sensors
    def xsensor(m):  # along x-axis
        return lambda state: state[id_pos][0] < m + 1

    for ind in xrange(X_BOUND):
        tmp_name = 'x' + str(ind)
        id_tmp, id_tmpc = EX.register_sensor(
            tmp_name)  #registers the sensor pairs
        EX.construct_sensor(id_tmp, xsensor(
            ind))  #constructs the measurables associated with the sensor
        EX.assign_sensor(id_tmp, True,
                         [id_rt, id_lt])  #assigns the sensor to all agents

    # normalized distance to playground (nav function #1)
    # - $id_distM$ has already been registerd
    def distM(state):
        if state[id_pos][0] == TARGET and state[id_pos][1] == TARGET:
            return state[id_distM][0] + 1
        else:
            #sharp (near-logarithmic) spike at the target
            #return 1.-np.log((1.+dist(state[id_pos][0],TARGET))/(X_BOUND+2))
            #linear peak at the target
            return 1 + X_BOUND - dist(state[id_pos][0], TARGET)

    INIT = 1 + X_BOUND - dist(START, TARGET)
    EX.construct_measurable(id_distM, distM, [INIT, INIT])

    def navM(state):
        return state[id_distM][0] - state[id_distM][1] > 0

    EX.construct_sensor(id_navM, navM)
    EX.assign_sensor(id_navM, True,
                     [id_rt, id_lt])  #assigns the sensor to all agents

    #
    ### Initialize agents on GPU
    #

    for agent_name in EX._AGENTS:
        tmp = EX._AGENTS[agent_name].init()

    #
    ### Introduce a conjunction
    #

    #for agent in [RT,LT]:
    #    agent.amper([agent.generate_signal([EX.nid('x0*'),EX.nid('x2')])])
    #

    ### Introduce delayed position sensors for both agents

    for agent in [RT, LT]:
        delay_sigs = [
            agent.generate_signal([EX.nid('x' + str(ind))])
            for ind in xrange(X_BOUND)
        ]
        agent.delay(delay_sigs)

    # another update cycle
    message = EX.update_state()
    #message=EX.update_state()

    ## SET ARTIFICIAL TARGET ONCE AND FOR ALL
    for agent in [RT, LT]:
        for token in ['plus', 'minus']:
            tmp_target = agent.generate_signal([id_navM]).value_all().tolist()
            agent.brain._snapshots[token].setTarget(tmp_target)

    #
    ### Run
    #

    # prepare windows for output
    curses.curs_set(0)
    stdscr.erase()

    # color definitions
    curses.init_color(0, 0, 0, 0)  #black=0
    curses.init_color(1, 1000, 0, 0)  #red=1
    curses.init_color(2, 0, 1000, 0)  #green=2
    curses.init_color(3, 1000, 1000, 0)  #yellow=3
    curses.init_color(4, 1000, 1000, 1000)  #white=4
    curses.init_color(5, 1000, 1000, 500)

    curses.init_pair(1, 0, 1)  #black on red
    curses.init_pair(2, 0, 2)  #green on black
    curses.init_pair(3, 0, 3)  #black on yellow
    curses.init_pair(4, 4, 0)  #white on black
    curses.init_pair(5, 1, 0)  #red on black
    curses.init_pair(6, 0, 5)

    REG_BG = curses.color_pair(4) | curses.A_BOLD
    POS_BG = curses.color_pair(2) | curses.A_BOLD
    NEG_BG = curses.color_pair(1) | curses.A_BOLD
    OBS_BG = curses.color_pair(6) | curses.A_BOLD
    BG = curses.color_pair(5) | curses.A_BOLD
    FG = curses.color_pair(3) | curses.A_BOLD

    WIN = curses.newwin(9, 2 * X_BOUND + 3, 5, 7)
    WINs = curses.newwin(9, 200, 16, 7)
    stdscr.nodelay(NODELAY)

    WIN.bkgdset(ord('.'), REG_BG)

    WIN.overlay(stdscr)
    WINs.overlay(stdscr)

    def print_state(text, id_agent):
        stdscr.clear()
        stdscr.addstr('W-E  A-R-E  R-U-N-N-I-N-G    (press [space] to stop) ')
        stdscr.addstr(2, 3, text)
        stdscr.clrtoeol()
        stdscr.noutrefresh()
        WIN.clear()
        WIN.addstr(0, 0, str(EX.this_state(id_count, 1)))
        WIN.chgat(0, 0, BG)

        ## Unpacking the output from the tested agent (RT/LT)

        #determining the start position of geographic sensors in signals
        geo_start = min(ind for ind, id_tmp in enumerate(LT._SENSORS)
                        if id_tmp == EX.nid('x0'))
        #decompose extra info from agent
        agent = EX._AGENTS[id_agent]
        curr = agent._CURRENT
        targ = agent._TARGET
        pred = agent._PREDICTED

        #choose the signals to visualize (curr,targ or pred)

        for ind, lookat in enumerate([curr, pred, targ]):
            #convert signals to region bounds
            bounds = {'plus': [0, X_BOUND], 'minus': [0, X_BOUND]}
            for token in ['plus', 'minus']:
                for x in xrange(0, X_BOUND):
                    if lookat[token].value(geo_start + 2 * x):
                        bounds[token][1] = x  #pushing down the upper bound
                        break
                    else:
                        continue
                for x in xrange(X_BOUND - 1, -1, -1):
                    if lookat[token].value(geo_start + 2 * x + 1):
                        bounds[token][0] = x + 1  #pushing up the lower bound
                        break
                    else:
                        continue

            #display the results
            tok_BG = {'plus': POS_BG, 'minus': NEG_BG}
            tok_line = {'plus': 3 - ind, 'minus': 6 + ind}
            for token in ['plus', 'minus']:
                min_pos = bounds[token][0]
                max_pos = bounds[token][1]
                for x in xrange(0, X_BOUND):
                    ori = ord('<') if lookat[token].value(
                        geo_start + 2 * x) else (
                            ord('>') if lookat[token].value(geo_start + 2 * x +
                                                            1) else ord('*'))
                    this_BG = tok_BG[token] if (x >= min_pos
                                                and x < max_pos) else BG
                    WIN.addch(tok_line[token], 2 + 2 * x, ori, this_BG)

                    WIN.chgat(tok_line[token], 1 + 2 * min_pos,
                              1 + 2 * (max_pos - min_pos), tok_BG[token])
        # display targets with FG attributes
        WIN.addch(5, 1 + 2 * TARGET, ord('T'), FG)
        # display agent's position with FG attributes
        WIN.addch(4, 1 + 2 * EX.this_state(id_pos, 1), ord('S'), FG)

        ## Unpacking extra information
        WINs.clear()
        WINs.addstr(0, 0, 'Observation:')
        WINs.addstr(4, 0, 'Chosen signed signal:')
        #
        tok_BG = {'plus': POS_BG, 'minus': NEG_BG}
        vpos = {'plus': 6, 'minus': 8}
        hpos = lambda x: 0 if x == 0 else 2 + len('  '.join(namelist[:x]))

        # CURRENT OBSERVATION
        OBS = agent._OBSERVE
        #OBS=Signal([EX.this_state(mid) for mid in agent._SENSORS])

        #SIGNED SIGNAL TO WATCH:
        #SIG=agent._CURRENT

        sig = agent.generate_signal([EX.nid('x0')])
        #sig=agent.generate_signal([EX.nid('{x0*;x2}')])
        #sig=agent.generate_signal([EX.nid('#x2')])
        #sig=agent.generate_signal([EX.nid('#x0*')])
        SIG = agent.brain.up(sig, False)
        #
        namelist = [EX.din(mid) for mid in agent._SENSORS]
        #
        for x, mid in enumerate(agent._SENSORS):
            this_BG = OBS_BG if OBS.value(x) else REG_BG
            WINs.addstr(2, hpos(x), namelist[x], this_BG)
            for token in ['plus', 'minus']:
                this_BG = tok_BG[token] if SIG[token].value(x) else REG_BG
                WINs.addstr(vpos[token], hpos(x), namelist[x], this_BG)

        # refresh the window
        WIN.overlay(stdscr)
        WIN.noutrefresh()
        WINs.noutrefresh()
        curses.doupdate()

    ## Main loop
    while stdscr.getch() != ord(' '):

        # call output subroutine
        print_state('RUNNING:\n' + message, id_lookat)

        # make decisions, update the state
        message = EX.update_state()

    else:
        raise Exception('Aborting at your request...\n\n')
Exemple #43
0
#encoding=utf-8

import curses

#Init terminal
scr = curses.initscr()
curses.start_color()
curses.noecho()
curses.cbreak()
scr.keypad(True)
curses.curs_set(False)

curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_GREEN)
curses.init_pair(2, curses.COLOR_CYAN, curses.COLOR_BLACK)

t = scr.subwin(12, 38, 0, 42)
t.box()
t.addstr(0,2,"< MIDI Input >")

import midi


t2=scr.subwin(10, 36, 1, 43)
t2.scrollok(True)

def add_data(msg):
	t2.scroll(1)
	t2.move(9,1)
	for c, tx in msg:
		t2.addstr(tx,curses.color_pair(c))
	t2.refresh()
Exemple #44
0
# start player in top left corner of board
INITIAL_PLAYER_ROW = BOARD_ROW + 1
INITIAL_PLAYER_COL = BOARD_COL + 1
# TODO - start the player in a random location

######### variables

# screen
screen = curses.initscr()

# allowing the colors red and green to be used with
# default background (-1)
curses.start_color()
curses.use_default_colors()
# player color is red (pair #1)
curses.init_pair(1, curses.COLOR_RED, -1)
# food color is green (pair #2)
curses.init_pair(2, curses.COLOR_GREEN, -1)
# TODO - learn more about color in Curses programming
# at https://docs.python.org/3/howto/curses.html#attributes-and-color

# game control flag variables
isGameOver = False

# game loop timer
# 1000 = 1 second, 100 = 1 tenth of a second
gameSpeed = 1000

# score
score = 0
def main(stdscr):
    # ==================
    # = Helper methods =
    # ==================
    paint_cell = lambda y, x, char, attr: stdscr.addstr(
        2 * (y + 1), 2 * (x + 1), char, attr)

    def count_bombs(current_y, current_x):
        return str(
            sum(
                sum(row[max(0, current_x - 1):min(width, current_x + 2)])
                for row in bombs[max(0, current_y -
                                     1):min(height, current_y + 2)]) or ' ')

    def click(current_y, current_x, user_click=True):
        if bombs[current_y][current_x]:
            if user_click:
                raise Exception(
                    'You clicked on a bomb 😥️. BOOM 💣️. YOU LOSE!! 💀️')

        if board[current_y][current_x] != '.':
            return

        neighbors = [(current_y, current_x)]

        while neighbors:
            current_y, current_x = neighbors.pop()

            board[current_y][current_x] = count_bombs(current_y, current_x)

            if board[current_y][current_x] == ' ':
                for offset_y in (-1, 0, 1):
                    new_y = current_y + offset_y

                    if new_y < 0 or new_y > height - 1:
                        continue

                    for offset_x in (-1, 0, 1):
                        new_x = current_x + offset_x

                        if new_x < 0 or new_x > width - 1 or offset_x == 0 and offset_y == 0:
                            continue

                        if board[new_y][new_x] != '.' or bombs[new_y][new_x]:
                            continue

                        neighbors.append((new_y, new_x))

    # ===============
    # = Screen init =
    # ===============

    curses.curs_set(0)
    curses.init_pair(1, curses.COLOR_RED, curses.COLOR_WHITE)

    # Clear screen
    stdscr.clear()

    # ===================
    # = Game state init =
    # ===================

    height, width = (curses.LINES - 2) // 2 - 1, (curses.COLS - 2) // 2 - 1
    current_y, current_x = 0, 0
    key = None

    bombs = [[random() < MINE_RATIO for x in range(0, width)]
             for y in range(0, height)]
    board = [['.' for x in range(0, width)] for y in range(0, height)]

    # ================
    # = Game routine =
    # ================
    finished = False
    while key != 'q' and not finished:
        finished = True

        stdscr.addstr(0, 0, '┌' + '─' * (2 * width + 1) + '┐')
        stdscr.addstr(2 * height + 1, 0, '└' + '─' * (2 * width + 1) + '┘')

        for y in range(0, height):
            stdscr.addstr(2 * (y + 1) - 1, 0, '│')
            stdscr.addstr(2 * (y + 1), 0, '│')
            stdscr.addstr(2 * (y + 1) - 1, 2 * width + 2, '│')
            stdscr.addstr(2 * (y + 1), 2 * width + 2, '│')

            for x in range(0, width):
                paint_cell(
                    y, x, board[y][x],
                    curses.color_pair(1) if
                    (y, x) == (current_y, current_x) else False)

                if board[y][x] == '.' or bombs[y][x] != (board[y][x]
                                                         == MINE_SYMBOL):
                    finished = False

        stdscr.refresh()
        key = stdscr.getkey()

        if key == 'KEY_LEFT':
            current_x = max(0, current_x - 1)
        elif key == 'KEY_RIGHT':
            current_x = min(width - 1, current_x + 1)
        elif key == 'KEY_UP':
            current_y = max(0, current_y - 1)
        elif key == 'KEY_DOWN':
            current_y = min(height - 1, current_y + 1)
        elif key == ' ':
            click(current_y, current_x)
        elif key == 'x':
            if board[current_y][current_x] == '.':
                board[current_y][current_x] = MINE_SYMBOL
            elif board[current_y][current_x] == MINE_SYMBOL:
                board[current_y][current_x] = '.'

    if finished:
        raise Exception('YOU WIN!! 🎉️🎉️')
    else:
        raise Exception('kthxbye')
def initializeChars():  #chars = '.#^!-*:++;[???---////()?[[[]]]]'
  global chars
  #these are the types of terrain and items

  chars = (	   ' ',	#  0 empty
		   '.',	#  1 floor
		   '@',	#  2 player
		   '<',	#  3 up stairs
		   '>',	#  4 down stairs
  curses.ACS_BLOCK,	#  5 filled in
  curses.ACS_HLINE,	#  6 \
  curses.ACS_VLINE,	#  7 |
  curses.ACS_ULCORNER,	#  8 | these are used for
  curses.ACS_URCORNER,	#  9 | room borders
  curses.ACS_LLCORNER,	# 10 |
  curses.ACS_LRCORNER,	# 11 /
  curses.ACS_CKBOARD,	# 12 door
# 13  14  15  16  17  18  19  20  21  22  23  24  25  26  27  28  29  30  31  32  33  34  35  36  37  38
  'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',
# 39  40  41  42  43  44  45  46  47  48  49  50  51  52  53  54  55  56  57  58  59  60  61  62  63  64
  'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'
#		   ' ',	# 65
  )

  #color combinaions of foreground, background
  curses.init_pair(9, curses.COLOR_WHITE, curses.COLOR_RED)
  curses.init_pair(10, curses.COLOR_RED, curses.COLOR_BLACK)
  curses.init_pair(11, curses.COLOR_YELLOW, curses.COLOR_BLACK)
  curses.init_pair(12, curses.COLOR_GREEN, curses.COLOR_BLACK)
  curses.init_pair(13, curses.COLOR_WHITE, curses.COLOR_GREEN)


  curses.init_pair(14, curses.COLOR_BLUE, curses.COLOR_BLACK)
  curses.init_pair(15, curses.COLOR_CYAN, curses.COLOR_BLACK)
  curses.init_pair(16, curses.COLOR_GREEN, curses.COLOR_BLACK)
  curses.init_pair(17, curses.COLOR_MAGENTA, curses.COLOR_BLACK)
  curses.init_pair(18, curses.COLOR_RED, curses.COLOR_BLACK)
  curses.init_pair(19, curses.COLOR_WHITE, curses.COLOR_BLACK)
  curses.init_pair(20, curses.COLOR_YELLOW, curses.COLOR_BLACK)
Exemple #47
0
import curses
from math import *



screen = curses.initscr()
curses.noecho()
curses.cbreak()
curses.start_color()
screen.keypad( 1 )
curses.init_pair(1,curses.COLOR_BLACK, curses.COLOR_CYAN)
highlightText = curses.color_pair( 1 )
normalText = curses.A_NORMAL
screen.border( 0 )
curses.curs_set( 0 )
max_row = 10 #max number of rows
box = 
box.box()


strings = [ "a", "b", "c", "d", "e", "f", "g", "h", "i", "l", "m", "n" ] #list of strings
row_num = len( strings )

pages = int( ceil( row_num / max_row ) )
position = 1
page = 1
for i in range( 1, max_row + 1 ):
    if row_num == 0:
        box.addstr( 1, 1, "There aren't strings", highlightText )
    else:
        if (i == position):
Exemple #48
0
def init_colors():
    curses.init_pair(1, curses.COLOR_RED, curses.COLOR_BLACK)
    curses.init_pair(2, curses.COLOR_GREEN, curses.COLOR_BLACK)
    curses.init_pair(3, curses.COLOR_BLUE, curses.COLOR_BLACK)
    curses.init_pair(4, curses.COLOR_YELLOW, curses.COLOR_BLACK)
Exemple #49
0
 def __init__(self, screen):
     curses.init_pair(3, curses.COLOR_BLACK, curses.COLOR_WHITE)
     self.screen = screen
     self.countdown = 0
     self.last_message = ''
Exemple #50
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

from time import sleep
import curses, os #curses is the interface for capturing key presses on the menu, os launches the files
screen = curses.initscr() #initializes a new window for capturing key presses
curses.noecho() # Disables automatic echoing of key presses (prevents program from input each key twice)
curses.cbreak() # Disables line buffering (runs each key as it is pressed rather than waiting for the return key to pressed)
curses.start_color() # Lets you use colors when highlighting selected menu option
#curses.resizeterm(20, 80)
screen.keypad(1) # Capture input from keypad

# Change this to use different colors when highlighting
curses.init_pair(1, curses.COLOR_BLACK, curses.COLOR_GREEN) # Sets up color pair #1, it does black text with white background
curses.init_pair(2, curses.COLOR_GREEN, curses.COLOR_BLACK)
h = curses.color_pair(1) #h is the coloring for a highlighted menu option
#n = curses.A_NORMAL #n is the coloring for a non highlighted menu option
n = curses.color_pair(2)

MENU = "menu"
COMMAND = "command"
EXITMENU = "exitmenu"

hellomsg = '*** WELCOME TO SWEARJAR BANK MAINFRAME SYSTEM ***'

menu_data = {
  'title': "IBM System/390, S/390 Version 2 Release 10 (May 2000)", 'type': MENU, 'subtitle': "---- Primary Option Menu ----",
  'options':[
        { 'title': "START DATABASE SERVICE", 'type': COMMAND, 'command': 'sudo service lighttpd start && python progress.py' },
        { 'title': "STOP DATABASE SERVICE", 'type': COMMAND, 'command': 'sudo service lighttpd stop && python progress.py' },
        { 'title': "BATCH", 'type': COMMAND, 'command': '' },
Exemple #51
0
def draw_menu(stdscr):
    k = 0
    count = 0

    # 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)

    # Get rid of the cursor
    curses.curs_set(0)

    # Loop where k is the last character pressed
    while k != ord("q"):

        # Initialization
        stdscr.clear()
        height, width = stdscr.getmaxyx()

        # Declaration of strings
        title = "The Count"[:width - 1]
        subtitle = "{}".format(count)[:width - 1]
        statusbarstr = (
            "Press 'q' to exit | Press 'b' to go back | Press 'r' to reset")

        # 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_y = int((height // 2) - 2)

        # Render status bar
        stdscr.attron(curses.color_pair(1))
        stdscr.addstr(height - 1, 0, 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, title)

        # Turning off attributes for title
        stdscr.attroff(curses.color_pair(2))
        stdscr.attroff(curses.A_BOLD)

        # Print rest of text
        stdscr.addstr(start_y + 1, start_x_subtitle, subtitle)
        stdscr.addstr(start_y + 3, (width // 2) - 3, "-" * 6)
        #stdscr.move(cursor_y, cursor_x)

        # Refresh the screen
        stdscr.refresh()

        # Wait for next input
        k = stdscr.getch()
        if k == ord('b'):
            count = count - 1
        elif k == ord('r'):
            count = 0
        else:
            count = count + 1
Exemple #52
0
    def get(self):
        """
        Handles key presses. Returns True if a key was found, False otherwise.
        """
        key_pressed = True
        try:
            kp = self.screen.getch()
        except:
            kp = None
            return False
        if kp == ord(" ") or kp == ord("q") or kp == 27:  #27 = ESC
            exit()
        elif kp == ord('-') or kp == ord('_') or kp == curses.KEY_LEFT:
            self.delay = min(self.delay + 10, 1000)
            self.show_speed()
        elif kp == ord('=') or kp == ord('+') or kp == curses.KEY_RIGHT:
            self.delay = max(self.delay - 10, 0)
            self.show_speed()
        elif kp == ord('[') or kp == curses.KEY_DOWN:
            self.delay = min(self.delay + 100, 1000)
            self.show_speed()
        elif kp == ord(']') or kp == curses.KEY_UP:
            self.delay = max(self.delay - 100, 0)
            self.show_speed()
        elif kp == ord('b'):
            self.cycle_bold()
        elif kp == ord('1'):
            curses.init_pair(1, curses.COLOR_GREEN, -1)
            self.stat.update('Green', self.delay)
        elif kp == ord('2'):
            curses.init_pair(1, curses.COLOR_RED, -1)
            self.stat.update('Red', self.delay)
        elif kp == ord('3'):
            curses.init_pair(1, curses.COLOR_BLUE, -1)
            self.stat.update('Blue', self.delay)
        elif kp == ord('4'):
            curses.init_pair(1, curses.COLOR_WHITE, -1)
            self.stat.update('White', self.delay)
        elif kp == ord('5'):
            curses.init_pair(1, curses.COLOR_YELLOW, -1)
            self.stat.update('Yellow', self.delay)
        elif kp == ord('6'):
            curses.init_pair(1, curses.COLOR_CYAN, -1)
            self.stat.update('Cyan', self.delay)
        elif kp == ord('7'):
            curses.init_pair(1, curses.COLOR_MAGENTA, -1)
            self.stat.update('Magenta', self.delay)
        elif kp == ord('8'):
            curses.init_pair(1, curses.COLOR_BLACK, -1)
            self.stat.update('Black', self.delay)
        elif kp == ord('o'):
            self.toggle_status()
        else:
            key_pressed = False

        return key_pressed
Exemple #53
0
    def draw(self, messageTitle, selected):
        # self.screen.clear()
        curses.start_color()
        curses.use_default_colors()
        curses.init_pair(1, curses.COLOR_BLACK, curses.COLOR_GREEN)
        curses.init_pair(2, curses.COLOR_BLACK, curses.COLOR_RED)
        ymax, xmax = self.screen.getmaxyx()
        x_start = int(xmax / 4)
        y_start = int(ymax / 4)
        for j in range(x_start, xmax):
            for i in range(y_start - 4, ymax):
                self.screen.move(i, j)
                try:
                    self.screen.addch(i, j, ' ')
                except Exception:
                    pass
        for i in range(x_start, x_start * 3 + 1):
            self.screen.move(y_start - 4, i)
            self.screen.addstr('=')
            self.screen.move(y_start, i)
            self.screen.addstr('=')
            if i >= x_start + 2 and i <= x_start * 3 - 1:
                self.screen.move(y_start + 2, i)
                self.screen.addstr('-')
            self.screen.move(y_start + 4, i)
            self.screen.addstr('=')
            self.screen.move(y_start + 6, i)
            self.screen.addstr('=')
        for i in range(y_start - 3, y_start + 6):
            if i == y_start:
                continue
            self.screen.move(i, x_start)
            self.screen.addstr('|')
            self.screen.move(i, x_start * 3)
            self.screen.addstr('|')
        true_x = x_start + int(x_start / 2)
        false_x = 2 * x_start + int(x_start / 3)
        self.screen.move(y_start + 5, true_x)
        if selected:
            self.screen.addstr('[' + self.True_text + ']',
                               curses.color_pair(1))
        else:
            self.screen.addstr('[' + self.True_text + ']')
        self.screen.move(y_start + 5, false_x)
        if selected:
            self.screen.addstr('[' + self.False_text + ']')
        else:
            self.screen.addstr('[' + self.False_text + ']',
                               curses.color_pair(2))

        # Print Title
        Title_x = (2 * x_start) - int(len(messageTitle) / 2)
        Title_y = y_start - 2
        self.screen.move(Title_y, Title_x)
        self.screen.addstr(messageTitle)

        # Print Message
        inputShow = ' ' + self.input + ' '
        x = (2 * x_start) - int(len(inputShow) / 2)
        y = y_start + 2
        self.screen.move(y, x)
        self.screen.addstr(inputShow)
Exemple #54
0
def main(win):
    jog = Jog()
    i = 0
    curses.start_color()
    curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK)
    curses.init_pair(2, curses.COLOR_BLUE, curses.COLOR_BLACK)
    curses.init_pair(3, curses.COLOR_RED, curses.COLOR_BLACK)
    curses.init_pair(4, curses.COLOR_YELLOW, curses.COLOR_BLACK)
    curses.halfdelay(2)
    curses.curs_set(0)
    win.clear()
    printSettings(win, jog)
    then = time.time()
    err = None
    inputBuffer = []
    dro = curses.newwin(5, 16, curses.LINES / 2 - 3, curses.COLS / 2 - 8)
    dro.border()
    #dro.addstr(0, 1, ' DRO ')
    while 1:
        try:
            ch = -1
            if jog.isComplete():
                cmd = jog.popCommand()
                if cmd:
                    cmd(jog)
                else:
                    if inputBuffer:
                        ch = inputBuffer[0]
                        inputBuffer = inputBuffer[1:]
                    else:
                        ch = win.getch()
                    axis = Key2Axis.get(ch)
                    jog.jog(axis, jog.mode == Jog.INCREMENT)
                    cmd = Key2Command.get(ch)
                    if cmd:
                        cmd(jog, win)
                        printSettings(win, jog)
                    if ord('q') == ch or ord('Q') == ch:
                        break
            else:
                ch = win.getch()
                cmd = Key2Command.get(ch)
                if cmd:
                    cmd(jog, win)
                    printSettings(win, jog)
                elif -1 != ch:
                    inputBuffer.append(ch)

            #if -1 != ch:
            #    win.addstr(0, 0, "%d" % ch)

            now = time.time()
            if True or (now - then) >= 0.1:
                i = (i + 1) % len(progr)
                #attr = curses.A_NORMAL if jog.mk.isOn() else curses.A_REVERSE
                if jog.mk.isOn():
                    if jog.mk.isHomed(False):
                        attr = curses.color_pair(1)
                    else:
                        attr = curses.color_pair(4)
                elif jog.mk.isEstop(False):
                    attr = curses.color_pair(3)
                else:
                    attr = curses.color_pair(2)
                win.addch(0, curses.COLS - 1, progr[i])
                printDRO(dro, jog.mk, attr)
                win.refresh()
                dro.refresh()
                then = now

            e = jog.mk.error()
            if e:
                kind, msg = e
                if kind in [linuxcnc.NML_ERROR, linuxcnc.OPERATOR_ERROR]:
                    msg = "ERROR: %s" % msg
                else:
                    msg = "INFO: %s" % msg
                win.addstr(curses.LINES - 2, 1,
                           "%s %s" % (time.strftime('%H:%M:%S'), msg))
                err = now
            elif err and (now - err) > 10:
                win.move(curses.LINES - 2, 1)
                win.clrtoeol()
                err = None

        except KeyboardInterrupt:
            jog.mk.update()
            if jog.mk.stat.task_mode == linuxcnc.MODE_MDI:
                jog.mk.cmd.abort()
            else:
                jog.stop()
            inputBuffer = []
    def __init__(self, screen, maze):
        self.maze = Maze(maze)
        self.mazeColumns = 0
        self.mazeRows = 0
        self.mazeSpaces = 0
        self.playerID = 0
        self.computerIDs = []
        self.players = []
        self.threads = []
        self.lock = threading.RLock()
        self.isComplete = False
        self.usingScreen = False
        self.screen = screen
        self.player = Player(0)
        self.computer = ComputerPlayer(1)

        curses.curs_set(0)
        curses.start_color()
        ### No Backgrounds ###
        curses.init_pair(1, 15, curses.COLOR_BLACK)  # white
        curses.init_pair(2, 7, curses.COLOR_BLACK)  # gray
        curses.init_pair(3, 8, curses.COLOR_BLACK)  # dark gray
        curses.init_pair(4, 9, curses.COLOR_BLACK)  # red
        curses.init_pair(5, 11, curses.COLOR_BLACK)  # yellow
        curses.init_pair(6, 10, curses.COLOR_BLACK)  # green
        curses.init_pair(7, 12, curses.COLOR_BLACK)  # blue
        curses.init_pair(8, 14, curses.COLOR_BLACK)  # cyan
        curses.init_pair(9, 13, curses.COLOR_BLACK)  # purple
        ### Blue ###
        curses.init_pair(10, 15, curses.COLOR_BLUE)  # white
        curses.init_pair(11, 10, curses.COLOR_BLUE)  # green
        curses.init_pair(12, 9, curses.COLOR_BLUE)  # red
        curses.init_pair(13, 11, curses.COLOR_BLUE)  # yellow

        self.CURSES_COLOR_DICT = {
            'white': {
                None: curses.color_pair(1),
                'blue': curses.color_pair(10)
            },
            'gray': {
                None: curses.color_pair(2)
            },
            'dark gray': {
                None: curses.color_pair(3)
            },
            'red': {
                None: curses.color_pair(4),
                'blue': curses.color_pair(12)
            },
            'yellow': {
                None: curses.color_pair(5),
                'blue': curses.color_pair(13)
            },
            'green': {
                None: curses.color_pair(6),
                'blue': curses.color_pair(11)
            },
            'blue': {
                None: curses.color_pair(7)
            },
            'cyan': {
                None: curses.color_pair(8)
            },
            'purple': {
                None: curses.color_pair(9)
            },
            None: {
                'blue': curses.color_pair(10)
            },
        }
Exemple #56
0
 def init_color_pair(self, index, fg, bg):
     if self.has_colors:
         curses.init_pair(index, fg, bg)
Exemple #57
0
def main():

    ## Input Defaults ##################################################

    R1 = 56000.0
    R2 = 6980.0
    VINMax = 45
    VRef = 5.0

    ## Constraints #####################################################

    ADCZMax = 10000  # Maximum Output Impedance towards ADC < 10k
    ADCResMin = 0.01  # Minimum required ADC resolution in V

    try:
        try:
            mw = curses.initscr()
            height, width = mw.getmaxyx()

            if height <= 24 or width < 60:
                curses.endwin()
                sys.stdout.write(
                    "Your terminal is too small to draw on. Please resize")
                exit(1)

            curses.curs_set(0)
            curses.noecho()
            mw.keypad(1)
            mw.nodelay(1)

            # Define some colors
            try:
                curses.start_color()
            except:
                pass
            curses.use_default_colors()
            curses.init_pair(1, curses.COLOR_BLACK, -1)
            curses.init_pair(2, curses.COLOR_GREEN, -1)
            curses.init_pair(3, curses.COLOR_BLUE, -1)
            curses.init_pair(4, curses.COLOR_WHITE, curses.COLOR_RED)
            curses.init_pair(5, curses.COLOR_MAGENTA, -1)
            curses.init_pair(6, curses.COLOR_GREEN, -1)
            curses.init_pair(7, curses.COLOR_RED, -1)
            curses.init_pair(8, curses.COLOR_WHITE, -1)
            curses.init_pair(9, curses.COLOR_WHITE, -1)
            col1 = curses.color_pair(1)
            cgrn = curses.A_BOLD | curses.color_pair(2)
            cgri = curses.A_STANDOUT | curses.A_BOLD | curses.color_pair(6)
            cblu = curses.color_pair(3)
            cred = curses.color_pair(4)
            col5 = curses.color_pair(5)
            bred = curses.color_pair(7)
            bwhi = curses.A_STANDOUT | curses.A_BOLD | curses.color_pair(9)

            VIN = 0
            SimDirection = "U"
            SimMode = 3  # 1=R1, 2=R2, 3=V
            SimRate = 0.01
            Run = True

            while 1:

                event = mw.getch()
                if event == ord("q"):
                    break
                elif event == ord("\t"):
                    SimMode = SimMode + 1
                    if SimMode > 3:
                        SimMode = 1
                    if SimMode < 3 and SimRate < 1:
                        SimRate = 1
                    if SimMode == 3 and SimRate >= 1:
                        SimRate = 0.1
                elif event == curses.KEY_UP:
                    SimDirection = "U"
                    if Run == False:
                        if SimMode == 1:
                            R1 = R1 + SimRate
                        if SimMode == 2:
                            R2 = R2 + SimRate
                        if SimMode == 3:
                            VIN = VIN + SimRate
                elif event == curses.KEY_DOWN:
                    SimDirection = "D"
                    if Run == False:
                        if SimMode == 1:
                            R1 = R1 - SimRate
                        if SimMode == 2:
                            R2 = R2 - SimRate
                        if SimMode == 3:
                            VIN = VIN - SimRate
                elif event == ord("+"):
                    if SimMode == 1:
                        if (SimRate * 2) < (1024**3):
                            SimRate = SimRate * 2
                    if SimMode == 2:
                        if (SimRate * 2) < (1024**3):
                            SimRate = SimRate * 2
                    if SimMode == 3:
                        if (SimRate * 2) < (VINMax / 4):
                            SimRate = SimRate * 2
                elif event == ord("-"):
                    if (SimRate / 2) > 0.001:
                        SimRate = SimRate / 2
                elif event == ord("p"):
                    Run = toggleRun(Run)
                elif event == ord(" "):
                    Run = toggleRun(Run)
                elif event == ord("1"):
                    R1 = float(updateR1(mw, height, width, R1))
                elif event == ord("2"):
                    R2 = float(updateR2(mw, height, width, R2))
                elif event == ord("m"):
                    VINMax = float(updateVINMax(mw, height, width, VINMax))
                elif event == ord("r"):
                    VRef = float(updateVRef(mw, height, width, VRef))

                if (VINMax * R2 / (R1 + R2)) > VRef:
                    ClipV = 0.001
                    while ClipV <= VINMax:
                        if (ClipV * R2 / (R1 + R2)) > VRef:
                            break
                        else:
                            ClipV = ClipV + 0.001

                    ClipP = 100 - (100 / VINMax * ClipV)
                    ClipD = round(20 / 100 * ClipP)
                else:
                    ClipD = False
                    UC = VRef - (VINMax * R2 / (R1 + R2))
                    UP = 100 / VRef * UC
                    UD = round(20 / 100 * UP)

                ########################################################
                ########################################################
                ## Formulas ############################################

                ########################################################
                # Voltage Divider Open-Circuit Output Voltage (Unloaded)

                VdOC = VIN * R2 / (R1 + R2)
                # FIXME: Add some math to estimate the loaded value

                ########################################################
                # Power Loss. Why care? To save power of course, every
                # little mA counts, especially in mobile/autonomous and
                # battery powered devices. If that's not enough of a
                # motivator, knowing how much power will be dissipated
                # helps determining, if the selected resitor's package
                # will be able to handle it. Also, the more power is
                # dissipated into heat, the more you have to fight
                # against temperature rise, which in turn will alter
                # the resistors characteristics and therefore the
                # precision and reliability of your measurement.

                VdI = VIN / (R1 + R2)
                P1 = R1 * (VdI**2)
                P2 = R2 * (VdI**2)

                ########################################################
                # Impedance Matching and "common wisdom":
                #
                # "Seriously? ADC input impedance usually is in the
                # Mega-Ohm Range, so you don't need to bother with
                # the output impedance of your voltage divider"
                #
                # Well, since a majority of projects use ATMega MC's
                # (like the Arduino), let's have a look into some datasheets:
                #
                # http://www.atmel.com/images/atmel-7766-8-bit-avr-atmega16u4-32u4_datasheet.pdf (24.7.1) Page 306
                # http://www.atmel.com/images/Atmel-8271-8-bit-AVR-Microcontroller-ATmega48A-48PA-88A-88PA-168A-168PA-328-328P_datasheet_Complete.pdf (24.6.1) Page 244
                #
                # "The ADC is optimized for analog signals with an output
                # impedance of approximately 10 kΩ or less. If such a
                # source is used, the sampling time will be negligible."
                #
                # Whuut???
                #
                # The problem with high source impedances arises when
                # you are switching the input multiplexer from one pin
                # to another. If you have two inputs, one at 0.5V and
                # one at 4.5V, when you switch from one to the other,
                # the input has to charge (or discharge) that 14 pF
                # capacitor. (See Figure in the datasheets)
                #
                # If the signal source is very high impedance, having to
                # charge the capacitor may cause the input voltage to
                # drop temporarily. If the ADC converts on the input
                # while is is still charging the capacitor, you will
                # get an incorrect value.
                #
                # This can probably be dealt with by letting the ADC
                # input settle for a period of time after switching
                # ADC channels, but the best way to deal with it is to
                # simply ensure that the input source can charge the
                # capacitance fast enough, so that it's not a problem.

                Zin = R1 + R2
                Zout = (R1 * R2) / (R1 + R2)

                ########################################################
                # ADC Resolution (Actual PIN Voltage)

                ADC8Res = VRef / (2**8)
                ADC10Res = VRef / (2**10)
                ADC12Res = VRef / (2**12)
                ADC16Res = VRef / (2**16)

                ########################################################
                # ADC Resolution (Full-Scale Voltage)

                ADC8FRes = (R1 / R2) * VRef / (2**8)
                ADC10FRes = (R1 / R2) * VRef / (2**10)
                ADC12FRes = (R1 / R2) * VRef / (2**12)
                ADC16FRes = (R1 / R2) * VRef / (2**16)

                ########################################################
                # ADC Decimal Output Prediction

                ADC8Dec = int((2**8) / VRef * VdOC)
                ADC10Dec = int((2**10) / VRef * VdOC)
                ADC12Dec = int((2**12) / VRef * VdOC)
                ADC16Dec = int((2**16) / VRef * VdOC)

                ########################################################
                # ADC Clipping Analysis

                if VdOC > VRef:
                    ADCClip = True
                else:
                    ADCClip = False

                # Protect Display from showing clipped values
                if ADC8Dec > (2**8):
                    ADC8Dec = (2**8)

                if ADC10Dec > (2**10):
                    ADC10Dec = (2**10)

                if ADC12Dec > (2**12):
                    ADC12Dec = (2**12)

                if ADC16Dec > (2**16):
                    ADC16Dec = (2**16)

                ########################################################
                # Calculate Pin Voltage from ADC's decimal value and
                # prevent further computation if DEC value is actually 0

                if ADC8Dec > 0:
                    VT8P = (ADC8Dec + 0.5) / (2**8) * VRef
                else:
                    VT8P = 0

                if ADC10Dec > 0:
                    VT10P = (ADC10Dec + 0.5) / (2**10) * VRef
                else:
                    VT10P = 0

                if ADC12Dec > 0:
                    VT12P = (ADC12Dec + 0.5) / (2**12) * VRef
                else:
                    VT12P = 0

                if ADC16Dec > 0:
                    VT16P = (ADC16Dec + 0.5) / (2**16) * VRef
                else:
                    VT16P = 0

                ########################################################
                # Calculate Full-Scale Voltage, can be copied directly
                # into the AVR/Arduino Firmware as a reference, integrating
                # or alongside the Pin Voltage calculation.

                VT8FS = VT8P / (R2 / (R1 + R2))
                VT10FS = VT10P / (R2 / (R1 + R2))
                VT12FS = VT12P / (R2 / (R1 + R2))
                VT16FS = VT16P / (R2 / (R1 + R2))

                ########################################################
                # Calculate Full-Scale Precision in mV

                VT8Prec = (VIN - VT8FS) * 1000
                VT10Prec = (VIN - VT10FS) * 1000
                VT12Prec = (VIN - VT12FS) * 1000
                VT16Prec = (VIN - VT16FS) * 1000

                ########################################################
                # Draw schema

                mw.addstr(3, 10, "  │  ", cgrn)
                mw.addstr(4, 10, " ┌┴┐ ", cblu)
                mw.addstr(5, 10, " │ │ ", cblu)
                mw.addstr(6, 10, " │ │ ", cblu)
                mw.addstr(7, 10, " │ │ ", cblu)
                mw.addstr(8, 10, " └┬┘ ", cblu)
                mw.addstr(9, 10, "  │  ", cgrn)
                mw.addstr(10, 10, "  ├─ ", cgrn)
                mw.addstr(11, 10, "  │  ", cgrn)
                mw.addstr(12, 10, " ┌┴┐ ", cblu)
                mw.addstr(13, 10, " │ │ ", cblu)
                mw.addstr(14, 10, " │ │ ", cblu)
                mw.addstr(15, 10, " │ │ ", cblu)
                mw.addstr(16, 10, " └┬┘ ", cblu)
                mw.addstr(17, 10, "  │  ", cgrn)
                mw.addstr(18, 10, "╶─┴─╴", cgrn)
                mw.addstr(19, 10, " ╶─╴ ", cgrn)
                mw.addstr(20, 10, "  ─  ", cgrn)
                mw.addstr(10, 25, "─────", cgrn)
                mw.addstr(1, 35, "┌───────┐", col5)
                mw.addstr(2, 35, "┤  ADC  │", col5)
                mw.addstr(3, 35, "│  256  ├▶", col5)
                mw.addstr(4, 33, "┌─┤ 8 Bit │", col5)
                mw.addstr(5, 33, "│ └───────┘", col5)
                mw.addstr(6, 33, "│ ┌───────┐", col5)
                mw.addstr(7, 35, "┤  ADC  │", col5)
                mw.addstr(8, 33, "│ │ 1024  ├▶", col5)
                mw.addstr(9, 33, "├─┤ 10Bit │", col5)
                mw.addstr(10, 33, "│ └───────┘", col5)
                mw.addstr(11, 33, "│ ┌───────┐", col5)
                mw.addstr(12, 35, "┤  ADC  │", col5)
                mw.addstr(13, 33, "│ │ 4096  ├▶", col5)
                mw.addstr(14, 33, "├─┤ 12Bit │", col5)
                mw.addstr(15, 33, "│ └───────┘", col5)
                mw.addstr(16, 33, "│ ┌───────┐", col5)
                mw.addstr(17, 35, "┤  ADC  │", col5)
                mw.addstr(18, 33, "│ │ 65536 ├▶", col5)
                mw.addstr(19, 33, "├─┤ 16Bit │", col5)
                mw.addstr(20, 33, "│ └───────┘", col5)
                mw.addstr(21, 33, "└─", col5)
                mw.addstr(2, 30, "┌────", cgrn)
                mw.addstr(3, 30, "│", cgrn)
                mw.addstr(4, 30, "│", cgrn)
                mw.addstr(5, 30, "│", cgrn)
                mw.addstr(6, 30, "│", cgrn)
                mw.addstr(7, 30, "├────", cgrn)
                mw.addstr(8, 30, "│", cgrn)
                mw.addstr(9, 30, "│", cgrn)
                mw.addstr(10, 30, "┤", cgrn)
                mw.addstr(11, 30, "│", cgrn)
                mw.addstr(12, 30, "├────", cgrn)
                mw.addstr(13, 30, "│", cgrn)
                mw.addstr(14, 30, "│", cgrn)
                mw.addstr(15, 30, "│", cgrn)
                mw.addstr(16, 30, "│", cgrn)
                mw.addstr(17, 30, "└────", cgrn)
                mw.addstr(
                    6,
                    8,
                    "R1",
                )
                mw.addstr(
                    5,
                    15,
                    "R:",
                )
                mw.addstr(
                    14,
                    8,
                    "R2",
                )
                mw.addstr(
                    13,
                    15,
                    "R:",
                )
                mw.addstr(10, 11, "▶", curses.A_BOLD)
                mw.addstr(2, 12, "▼", curses.A_BOLD)
                mw.addstr(22, 24, "▼", curses.A_BOLD)
                mw.addstr(21, 35, "◀", curses.A_BOLD)
                mw.addstr(23, 4, "░░░░░░░░░░░░░░░░░░░░│░░░░░░░░░░░░░░░░░░░░",
                          curses.A_DIM | curses.color_pair(8))
                mw.addstr(
                    height - 1, 1,
                    "R[1] R[2] V[M]ax V[R]ef [+]Rate[-] [ ]Dir[ ] [P]ause [Q]uit"
                )

                if SimDirection == "U":
                    mw.addstr(height - 1, 37, "▲", cgrn)
                    mw.addstr(height - 1, 43, "▼")
                else:
                    mw.addstr(height - 1, 37, "▲")
                    mw.addstr(height - 1, 43, "▼", cgrn)

                ########################################################
                # Draw values

                if SimMode == 3:
                    mw.addstr(1, 8, str('  %.2f V  ' % VIN),
                              curses.A_STANDOUT | curses.A_BOLD)
                else:
                    mw.addstr(1, 8, str('  %.2f V  ' % VIN), curses.A_BOLD)

                mw.addstr(21, 36, str(' %.1f V ' % VRef),
                          curses.A_STANDOUT | curses.A_BOLD | col5)
                mw.addstr(21, 9, str('%.3f mA ' % (VdI * 1000)))

                if SimMode == 1:
                    mw.addstr(5, 18, str(' %d Ω ' % R1),
                              curses.A_STANDOUT | curses.A_BOLD)
                else:
                    mw.addstr(5, 18, str(' %d Ω ' % R1))

                mw.addstr(7, 15, str('P: %.3f mW ' % (P1 * 1000)))

                if SimMode == 2:
                    mw.addstr(13, 18, str(' %d Ω ' % R2),
                              curses.A_STANDOUT | curses.A_BOLD)
                else:
                    mw.addstr(13, 18, str(' %d Ω ' % R2))

                mw.addstr(15, 15, str('P: %.3f mW ' % (P2 * 1000)))

                if ClipD:
                    mw.addstr(
                        24, 10,
                        str('Clipping > %.2f V (%.1f%%) ' % (ClipV, ClipP)),
                        curses.A_BOLD | curses.A_BLINK)
                    mw.addstr(23, 1, "┌─▶", curses.A_BOLD)
                    mw.addstr(24, 1, "└────", curses.A_BOLD)
                    #mw.addstr( 23, 45, " ")
                    for i in range(0, ClipD):
                        mw.addstr(23, 23 - i, "▓", bred)
                    TDEff = 100 - ClipP
                else:
                    mw.addstr(
                        24, 8,
                        str('Wasted Resolution < %.2f V (%.1f%%) ' % (UC, UP)),
                        curses.A_BOLD)
                    mw.addstr(23, 45, "◀─┐", curses.A_BOLD)
                    mw.addstr(24, 43, "────┘", curses.A_BOLD)
                    #mw.addstr( 23, 3, " ")
                    for i in range(0, UD):
                        mw.addstr(23, 25 + i, "▓", bred)
                    TDEff = 100 - UP

                if TDEff >= 100:
                    mw.addstr(21, 21, str(' %d%% ' % TDEff), cgri)
                elif TDEff > 95:
                    mw.addstr(21, 21, str(' %.1f%% ' % TDEff), cgri)
                else:
                    mw.addstr(21, 21, str(' %.1f%% ' % TDEff), bred)

                if VdOC <= VRef:
                    mw.addstr(10, 2, str(' %.3f V ' % VdOC),
                              curses.A_BOLD | cgri)
                else:
                    mw.addstr(10, 1, str('! %.3f V ' % VdOC),
                              curses.A_BOLD | cred)

                if Zout <= ADCZMax:
                    mw.addstr(10, 15, str('Z: %d Ω' % Zout),
                              curses.A_BOLD | cgrn)
                else:
                    mw.addstr(10, 15, str('Z: %d Ω' % Zout), cred)

                if ADC8FRes <= ADCResMin:
                    mw.addstr(2, 46,
                              str(' Res: %.2f mV    ' % (ADC8FRes * 1000)),
                              cgrn)
                else:
                    mw.addstr(2, 45,
                              str('! Res: %.2f mV   ' % (ADC8FRes * 1000)),
                              cred)

                if not ADCClip:
                    mw.addstr(3, 46, str(' DEC: %d    ' % ADC8Dec))
                    mw.addstr(4, 46,
                              str(' %.2f V (%+d mV)    ' % (VT8FS, VT8Prec)),
                              curses.A_BOLD | cgrn)
                else:
                    mw.addstr(3, 45, str('! DEC: %d   ' % ADC8Dec), cred)
                    mw.addstr(4, 45,
                              str('! %.2f V (%+d mV)   ' % (VT8FS, VT8Prec)),
                              cred)

                if ADC10FRes <= ADCResMin:
                    mw.addstr(7, 46,
                              str(' Res: %.2f mV    ' % (ADC10FRes * 1000)),
                              cgrn)
                else:
                    mw.addstr(7, 45,
                              str('! Res: %.2f mV   ' % (ADC10FRes * 1000)),
                              cred)

                if not ADCClip:
                    mw.addstr(8, 46, str(' DEC: %d    ' % ADC10Dec))
                    mw.addstr(9, 46,
                              str(' %.2f V (%+d mV)    ' % (VT10FS, VT10Prec)),
                              curses.A_BOLD | cgrn)
                else:
                    mw.addstr(8, 45, str('! DEC: %d   ' % ADC10Dec), cred)
                    mw.addstr(9, 45,
                              str('! %.2f V (%+d mV)   ' % (VT10FS, VT10Prec)),
                              cred)

                if ADC12FRes <= ADCResMin:
                    mw.addstr(12, 46,
                              str(' Res: %.2f mV    ' % (ADC12FRes * 1000)),
                              cgrn)
                else:
                    mw.addstr(12, 45,
                              str('! Res: %.2f mV   ' % (ADC12FRes * 1000)),
                              cred)

                if not ADCClip:
                    mw.addstr(13, 46, str(' DEC: %d    ' % ADC12Dec))
                    mw.addstr(14, 46,
                              str(' %.2f V (%+d mV)    ' % (VT12FS, VT12Prec)),
                              curses.A_BOLD | cgrn)
                else:
                    mw.addstr(13, 45, str('! DEC: %d   ' % ADC12Dec), cred)
                    mw.addstr(14, 45,
                              str('! %.2f V (%+d mV)   ' % (VT12FS, VT12Prec)),
                              cred)

                if ADC16FRes <= ADCResMin:
                    mw.addstr(17, 46,
                              str(' Res: %.2f mV    ' % (ADC16FRes * 1000)),
                              cgrn)
                else:
                    mw.addstr(17, 45,
                              str('! Res: %.2f mV   ' % (ADC16FRes * 1000)),
                              cred)

                if not ADCClip:
                    mw.addstr(18, 46, str(' DEC: %d    ' % ADC16Dec))
                    mw.addstr(19, 46,
                              str(' %.2f V (%+d mV)    ' % (VT16FS, VT16Prec)),
                              curses.A_BOLD | cgrn)
                else:
                    mw.addstr(18, 45, str('! DEC: %d   ' % ADC16Dec), cred)
                    mw.addstr(19, 45,
                              str('! %.2f V (%+d mV)  ' % (VT16FS, VT16Prec)),
                              cred)

                if Run == True:

                    if SimMode == 1:
                        if SimDirection == "U":
                            R1 = R1 + SimRate
                        elif SimDirection == "D":
                            R1 = R1 - SimRate

                    if SimMode == 2:
                        if SimDirection == "U":
                            R2 = R2 + SimRate
                        elif SimDirection == "D":
                            R2 = R2 - SimRate

                    if SimMode == 3:
                        if SimDirection == "U":
                            VIN = VIN + SimRate
                        elif SimDirection == "D":
                            VIN = VIN - SimRate

                        if VIN > VINMax:
                            SimDirection = "D"
                            VIN = VINMax
                        elif VIN <= 0:
                            VIN = 0
                            SimDirection = "U"

                mw.refresh()
                time.sleep(0.15)

        except KeyboardInterrupt:
            pass
    finally:
        curses.nocbreak()
        curses.echo()
        curses.endwin()
Exemple #58
0
    def draw(self, messageTitle, messageText):
        # self.screen.clear()
        curses.start_color()
        curses.use_default_colors()
        ymax, xmax = self.screen.getmaxyx()
        x_start = int(xmax / 4)
        y_start = int(ymax / 4)
        for j in range(x_start, xmax):
            for i in range(y_start - 4, ymax):
                self.screen.move(i, j)
                try:
                    self.screen.addch(i, j, ' ')
                except Exception:
                    pass
        for i in range(x_start, x_start * 3 + 1):
            self.screen.move(y_start - 4, i)
            self.screen.addstr('=')
            self.screen.move(y_start, i)
            self.screen.addstr('=')
            self.screen.move(y_start * 3 - 4, i)
            self.screen.addstr('-')
            self.screen.move(y_start * 3, i)
            self.screen.addstr('=')
        for i in range(y_start - 3, y_start * 3):
            if i == y_start:
                continue
            self.screen.move(i, x_start)
            self.screen.addstr('|')
            self.screen.move(i, x_start * 3)
            self.screen.addstr('|')

        # Print MessageBox Buttons
        for indx, button in enumerate(self.Buttons):
            curses.init_pair(indx + 1, button['ForeColor'],
                             button['BackColor'])
            pos_x = (x_start + ((len(self.Buttons) - indx) * int(
                (2 * x_start) /
                (len(self.Buttons) + 1)))) - int(len(button['Text']) / 2)
            self.screen.move(y_start * 3 - 2, pos_x)
            if self.selected == indx:
                self.screen.addstr('[' + button['Text'] + ']',
                                   curses.color_pair(indx + 1))
            else:
                self.screen.addstr('[' + button['Text'] + ']')

        # Print Title
        Title_x = (2 * x_start) - int(len(messageTitle) / 2)
        Title_y = y_start - 2
        self.screen.move(Title_y, Title_x)
        self.screen.addstr(messageTitle)

        # Print Message
        lineMaxLength = 2 * x_start - int(x_start / 2)
        if '\n' in messageText:
            messageLines = messageText.split('\n')
        else:
            messageLines = []
            string = ""
            for i in messageText.split():
                if len(string) + len(i) + 1 <= lineMaxLength:
                    string += ' ' + i
                else:
                    messageLines.append(string)
                    string = i
            if string != "":
                messageLines.append(string)
        y = y_start
        end = y_start * 3 - 6
        messageFieldSize = int((end - y - 2) / 2) + 1
        maxAvailIndex = len(messageLines) - messageFieldSize
        if len(messageLines) <= messageFieldSize:
            self.startIndex = 0
        elif self.startIndex > maxAvailIndex:
            self.startIndex = maxAvailIndex
        for ml in messageLines[self.startIndex:]:
            x = (2 * x_start) - int(len(ml) / 2)
            y += 2
            if y > end:
                break
            self.screen.move(y, x)
            self.screen.addstr(ml)
Exemple #59
0
def main(stdscr):
    curses.curs_set(0)
    stdscr.nodelay(1)
    stdscr.timeout(400)
    sh, sw = stdscr.getmaxyx()
    box = [[3, 3], [sh - 3, sw - 3]]
    textpad.rectangle(stdscr, box[0][0], box[0][1], box[1][0], box[1][1])

    curses.init_pair(1, curses.COLOR_RED, curses.COLOR_BLACK)
    curses.init_pair(2, curses.COLOR_GREEN, curses.COLOR_BLACK)
    curses.init_pair(3, curses.COLOR_YELLOW, curses.COLOR_BLACK)
    curses.init_pair(4, curses.COLOR_BLUE, curses.COLOR_BLACK)

    curses.init_pair(5, curses.COLOR_CYAN, curses.COLOR_BLACK)

    counter = 1
    for line in art_lines:
        stdscr.addstr(counter + 5, sw // 2 - len(line) // 2, line)
        counter += 1

    counter = 1
    for instruc in instructions:
        stdscr.addstr(counter + (sh - len(instructions) - 5),
                      sw - len(instruc) - 5, instruc)
        counter += 1

    counter = 1
    for instruc2 in instructions2:
        stdscr.addstr(counter + (sh - len(instructions) - 2),
                      len(instruc) - 10, instruc2)
        counter += 1

    stdscr.attron(curses.color_pair(5))
    counter = 1
    for line in fire:
        stdscr.addstr(counter + 5, sw // 6 - len(line) // 2, line)
        counter += 1

    counter = 1
    for line in fire:
        stdscr.addstr(counter + 5, 5 * (sw // 6) - len(line) // 2, line)
        counter += 1
    stdscr.attroff(curses.color_pair(5))

    paddle = '[=====]'
    clear_paddle = '       '

    vertical_paddle = ['--', '||', '||', '||', "--"]

    clear_vertical_paddle = ['    ', '    ', '    ', '    ', '    ', "    "]

    start_msg = 'Press (s) to start!'

    top_paddle_position = sw // 2 - len(paddle) // 2
    bottom_paddle_position = sw // 2 - len(paddle) // 2

    left_paddle_position = 18 * (sh // 20) + 1
    right_paddle_position = 18 * (sh // 20) + 1

    stdscr.attron(curses.color_pair(1))
    stdscr.addstr(sh // 2, top_paddle_position, paddle)
    stdscr.attroff(curses.color_pair(1))

    stdscr.attron(curses.color_pair(2))
    stdscr.addstr(4 * (sh // 5), bottom_paddle_position, paddle)
    stdscr.attroff(curses.color_pair(2))

    counter = 0
    stdscr.attron(curses.color_pair(3))
    for line_left in vertical_paddle:
        stdscr.addstr(
            left_paddle_position - len(vertical_paddle) // 2 + counter,
            1 * (sw // 3), line_left)
        counter += 1
    stdscr.attroff(curses.color_pair(3))

    counter = 0
    stdscr.attron(curses.color_pair(4))
    for line_right in vertical_paddle:
        stdscr.addstr(
            right_paddle_position - len(vertical_paddle) // 2 + counter,
            2 * (sw // 3), line_right)
        counter += 1
    stdscr.attroff(curses.color_pair(4))

    stdscr.addstr(18 * (sh // 20), sw // 2 - len(start_msg) // 2, start_msg)

    LEFT_MAX = 2 * (sw // 5) - len(paddle) // 2
    RIGHT_MAX = 3 * (sw // 5) - len(paddle) // 2

    TOP_MAX = sh // 2 - 5
    BOTTOM_MAX = 4 * (sh // 5) + 5

    top_direction = 'LEFT'
    bottom_direction = 'RIGHT'
    left_direction = 'UP'
    right_direction = 'DOWN'

    number_players = 1

    while 1:
        key = stdscr.getch()
        if key == ord('s'):
            break

        stdscr.addstr(sh // 2, top_paddle_position, clear_paddle)
        stdscr.addstr(4 * (sh // 5), bottom_paddle_position, clear_paddle)

        counter = 0
        stdscr.attron(curses.color_pair(3))
        for line_left in clear_vertical_paddle:
            stdscr.addstr(
                left_paddle_position - len(vertical_paddle) // 2 + counter,
                1 * (sw // 3), line_left)
            counter += 1
        stdscr.attroff(curses.color_pair(3))

        counter = 0
        stdscr.attron(curses.color_pair(4))
        for line_right in clear_vertical_paddle:
            stdscr.addstr(
                right_paddle_position - len(vertical_paddle) // 2 + counter,
                2 * (sw // 3), line_right)
            counter += 1
        stdscr.attroff(curses.color_pair(4))

        # stdscr.addstr(left_paddle_position, 1*(sw//3), clear_vertical_paddle)
        # stdscr.addstr(right_paddle_position, 2*(sw//3), clear_vertical_paddle)

        if top_paddle_position <= LEFT_MAX and top_direction == 'LEFT':
            top_direction = 'RIGHT'
        elif top_paddle_position >= RIGHT_MAX and top_direction == 'RIGHT':
            top_direction = 'LEFT'

        if bottom_paddle_position <= LEFT_MAX and bottom_direction == 'LEFT':
            bottom_direction = 'RIGHT'
        elif bottom_paddle_position >= RIGHT_MAX and bottom_direction == 'RIGHT':
            bottom_direction = 'LEFT'

        if left_paddle_position <= BOTTOM_MAX and left_direction == 'DOWN':
            left_direction = 'UP'
        elif left_paddle_position >= TOP_MAX and left_direction == 'UP':
            left_direction = 'DOWN'

        if right_paddle_position <= BOTTOM_MAX and right_direction == 'DOWN':
            right_direction = 'UP'
        elif right_paddle_position >= TOP_MAX and right_direction == 'UP':
            right_direction = 'DOWN'

        if top_direction == 'LEFT':
            top_paddle_position -= 1
        else:
            top_paddle_position += 1

        if bottom_direction == 'LEFT':
            bottom_paddle_position -= 1
        else:
            bottom_paddle_position += 1

        if left_direction == 'DOWN':
            left_paddle_position += 1
        else:
            left_paddle_position -= 1

        if right_direction == 'DOWN':
            right_paddle_position += 1
        else:
            right_paddle_position -= 1

        stdscr.attron(curses.color_pair(1))
        stdscr.addstr(sh // 2, top_paddle_position, paddle)
        stdscr.attroff(curses.color_pair(1))

        stdscr.attron(curses.color_pair(2))
        stdscr.addstr(4 * (sh // 5), bottom_paddle_position, paddle)
        stdscr.attroff(curses.color_pair(2))

        # stdscr.attron(curses.color_pair(3))
        # stdscr.addstr(left_paddle_position, 1*(sw//3), vertical_paddle)
        # stdscr.attroff(curses.color_pair(3))

        counter = 0
        stdscr.attron(curses.color_pair(3))
        for line_left in vertical_paddle:
            stdscr.addstr(
                left_paddle_position - len(vertical_paddle) // 2 + counter,
                1 * (sw // 3), line_left)
            counter += 1
        stdscr.attroff(curses.color_pair(3))

        # stdscr.attron(curses.color_pair(4))
        # stdscr.addstr(right_paddle_position, 2*(sw//3), vertical_paddle)
        # stdscr.attroff(curses.color_pair(4))

        counter = 0
        stdscr.attron(curses.color_pair(4))
        for line_right in vertical_paddle:
            stdscr.addstr(
                right_paddle_position - len(vertical_paddle) // 2 + counter,
                2 * (sw // 3), line_right)
            counter += 1
        stdscr.attroff(curses.color_pair(4))

        stdscr.refresh()

    stdscr.getch()
Exemple #60
0
def map_demo(screen):
    curses.curs_set(0)
    map_model = [[empty.copy() for x in range(140)] for y in range(119)]
    for y, row in enumerate(map_model):
        for x, tile in enumerate(row):
            if x <= 19 or y <= 9 or x >= 80 or y >= 90:
                map_model[y][x] = wall.copy()

    heightmap = create_heightmap(80, 60)
    for y, row in enumerate(heightmap):
        for x, height in enumerate(row):
            point_y = y + 10
            point_x = x + 20
            if height < 0.1:
                map_model[point_y][point_x] = water.copy()
            elif height >= 0.1 and height < 0.2:
                map_model[point_y][point_x] = grass.copy()
            elif height >= 0.2 and height < 1.95:
                map_model[point_y][point_x] = empty.copy()
            elif height >= 1.95 and height < 2.0:
                map_model[point_y][point_x] = grass.copy()
            elif height >= 2.0 and height < 2.3:
                map_model[point_y][point_x] = empty.copy()
            elif height >= 2.3 and height < 2.4:
                map_model[point_y][point_x] = grass.copy()
            elif height >= 2.4 and height < 3.1:
                map_model[point_y][point_x] = tree.copy()
            elif height >= 3.1:
                map_model[point_y][point_x] = mountain.copy()

    map = ''.join(str(tile["char"]) for rows in map_model for tile in rows)

    items = []

    topLeftY = 0
    topLeftX = 0

    mapHeight = 20
    mapWidth = 40

    map_pad = curses.newpad(120, 140)

    num_rows, num_cols = screen.getmaxyx()

    middle_row = int(num_rows / 2)
    half_width_of_map = int(mapWidth / 2)
    middle_column = int(num_cols / 2)
    x_position = middle_column - half_width_of_map
    half_height_of_map = int(mapHeight / 2)
    y_position = middle_row - half_height_of_map

    running = True
    while (running):
        map_pad.erase()
        map_pad.addstr(0, 0, map)
        curses.init_pair(1, curses.COLOR_RED, curses.COLOR_WHITE)
        player_x = topLeftX + half_width_of_map
        player_y = topLeftY + half_height_of_map
        for it in items:
            map_pad.addstr(it["y"], it["x"], it["char"])

        map_pad.addstr(player_y, player_x, '@', curses.color_pair(1))
        map_pad.refresh(topLeftY, topLeftX, y_position, x_position, y_position + mapHeight, x_position + mapWidth)

        try:
            c = screen.getkey()

            if (str(c) == '\x1b'):
                running = False
            if (str(c) == 'w'):
                topLeftY = max(0, topLeftY - 1)
            if (str(c) == 's'):
                topLeftY = min(79, topLeftY + 1)
            if (str(c) == 'a'):
                topLeftX = max(0, topLeftX - 1)
            if (str(c) == 'd'):
                topLeftX = min(59, topLeftX + 1)
        except:
            num_rows, num_cols = screen.getmaxyx()

            middle_row = int(num_rows / 2)
            half_width_of_map = int(mapWidth / 2)
            middle_column = int(num_cols / 2)
            x_position = middle_column - half_width_of_map
            half_height_of_map = int(mapHeight / 2)
            y_position = middle_row - half_height_of_map
            screen.erase()
            screen.refresh()