Python curses 模块,has_colors() 实例源码

我们从Python开源项目中,提取了以下19个代码示例,用于说明如何使用curses.has_colors()

项目:defuse_division    作者:lelandbatey    | 项目源码 | 文件源码
def colors_init():
    """
    Initializes all color pairs possible into the dictionary CURSES_COLORPAIRS.
    Thus, getting an attribute for a black foreground and a green background
    would look like:
        >>> curses_color.colors_init()
        >>> green_black_attr = curses_color.CURSES_COLORPAIRS['black-green']
        >>> stdscr.addstr(0, 0, "test", curses.color_pair(green_black_attr))
    """
    if len(CURSES_COLORPAIRS): return
    assert curses.has_colors(
    ), "Curses wasn't configured to support colors. Call curses.start_color()"
    start_number = 120
    for fg in BASE_CURSES_COLORS.keys():
        for bg in BASE_CURSES_COLORS.keys():
            pair_num = len(CURSES_COLORPAIRS) + start_number
            curses.init_pair(pair_num, BASE_CURSES_COLORS[fg],
                             BASE_CURSES_COLORS[bg])
            pair_name = "{}-{}".format(fg, bg)
            CURSES_COLORPAIRS[pair_name] = pair_num
项目:captiv8    作者:wraith-wireless    | 项目源码 | 文件源码
def initcolors():
    """ initialize color pallet """
    curses.start_color()
    if not curses.has_colors():
        raise RuntimeError("Sorry. Terminal does not support colors")

    # setup colors on black background
    for i in range(1,9):
        curses.init_pair(i,i,BLACK)
        CPS[i] = curses.color_pair(i)

    # have to individually set up special cases
    curses.init_pair(BUTTON,WHITE,GRAY)     # white on gray for buttons
    CPS[BUTTON] = curses.color_pair(BUTTON)
    curses.init_pair(HLITE,BLACK,GREEN)     # black on Green for highlight aps,stas
    CPS[HLITE] = curses.color_pair(HLITE)
    curses.init_pair(ERR,WHITE,RED)         # white on red
    CPS[ERR] = curses.color_pair(ERR)
    curses.init_pair(WARN,BLACK,YELLOW)     # white on yellow
    CPS[WARN] = curses.color_pair(WARN)
    curses.init_pair(NOTE,WHITE,GREEN)      # white on red
    CPS[NOTE] = curses.color_pair(NOTE)
项目:defuse_division    作者:lelandbatey    | 项目源码 | 文件源码
def dotheui(stdscr, args):
    '''
    Here we springboard into the various bits of user interface.
    '''
    color_err = '''
This terminal doesn't support color, so we cannot start the game. You can try to force this by changing the environment variable named `TERM` to be a string that tells Curses that this terminal supports colors. One way to do this would be to enter the following string on your terminal:

    TERM=xterm-256color

After you've set this environment variable, try to launch DefuseDivision as you normally would. Some characters may display incorrectly, or look odd, but hopefully you'll be able to play :)
    '''
    if not curses.has_colors():
        return color_err
    if args.host is None:
        try:
            uiopts = mainmenu.mainmenu(stdscr)
        except KeyboardInterrupt:
            return ""
        except curses.error as err:
            if 'init_pair()' in str(err):
                return color_err
            else:
                raise err
    else:
        uiopts = {'mode': 'Multiplayer'}
        uiopts['connection'] = dict()
        uiopts['connection']['hostname'] = args.host
        port = args.port
        if port is None:
            port = 44444
        uiopts['connection']['port'] = port
    client = instance_setup.create_client(stdscr, args, uiopts)
    stdscr.clear()
    return tc.main(stdscr, client, args)
项目:sandsifter    作者:xoreaxeaxeax    | 项目源码 | 文件源码
def init_colors(self):

        if curses.has_colors() and curses.can_change_color():
            curses.init_color(self.COLOR_BLACK, 0, 0, 0)
            curses.init_color(self.COLOR_WHITE, 1000, 1000, 1000)
            curses.init_color(self.COLOR_BLUE, 0, 0, 1000)
            curses.init_color(self.COLOR_RED, 1000, 0, 0)
            curses.init_color(self.COLOR_GREEN, 0, 1000, 0)

            for i in xrange(0, self.GRAYS):
                curses.init_color(
                        self.GRAY_BASE + i,
                        i * 1000 / (self.GRAYS - 1),
                        i * 1000 / (self.GRAYS - 1),
                        i * 1000 / (self.GRAYS - 1)
                        )
                curses.init_pair(
                        self.GRAY_BASE + i,
                        self.GRAY_BASE + i,
                        self.COLOR_BLACK
                        )

        else:
            self.COLOR_BLACK = curses.COLOR_BLACK
            self.COLOR_WHITE = curses.COLOR_WHITE
            self.COLOR_BLUE = curses.COLOR_BLUE
            self.COLOR_RED = curses.COLOR_RED
            self.COLOR_GREEN = curses.COLOR_GREEN

            for i in xrange(0, self.GRAYS):
                curses.init_pair(
                        self.GRAY_BASE + i,
                        self.COLOR_WHITE,
                        self.COLOR_BLACK
                        )

        curses.init_pair(self.BLACK, self.COLOR_BLACK, self.COLOR_BLACK)
        curses.init_pair(self.WHITE, self.COLOR_WHITE, self.COLOR_BLACK)
        curses.init_pair(self.BLUE, self.COLOR_BLUE, self.COLOR_BLACK)
        curses.init_pair(self.RED, self.COLOR_RED, self.COLOR_BLACK)
        curses.init_pair(self.GREEN, self.COLOR_GREEN, self.COLOR_BLACK)
项目:culour    作者:shohamp    | 项目源码 | 文件源码
def _inner_addstr(window, string, y=-1, x=-1):
    assert curses.has_colors(), "Curses wasn't configured to support colors. Call curses.start_color()"

    cur_y, cur_x = window.getyx()
    if y == -1:
        y = cur_y
    if x == -1:
        x = cur_x
    for line in string.split(os.linesep):
        _add_line(y, x, window, line)
        # next line
        y += 1
项目:isar    作者:ilbers    | 项目源码 | 文件源码
def __init__( self, x, y, width, height, fg=curses.COLOR_BLACK, bg=curses.COLOR_WHITE ):
            self.win = curses.newwin( height, width, y, x )
            self.dimensions = ( x, y, width, height )
            """
            if curses.has_colors():
                color = 1
                curses.init_pair( color, fg, bg )
                self.win.bkgdset( ord(' '), curses.color_pair(color) )
            else:
                self.win.bkgdset( ord(' '), curses.A_BOLD )
            """
            self.erase()
            self.setScrolling()
            self.win.noutrefresh()
项目:grbl-stream    作者:fragmuffin    | 项目源码 | 文件源码
def render(self, strong=False):
        (y, x) = self.window.getmaxyx()
        label_str = " {} ".format(self._label)
        addstr_params = [
            self.row, self.label_col, " {} ".format(self._label),
            curses.color_pair(self.color_index) if curses.has_colors() else 0
        ]

        # heading attributes
        attrs = curses.color_pair(self.color_index) if curses.has_colors() else 0
        if strong:
            attrs |= curses.A_BOLD

        self.window.hline(0, 0, curses.ACS_HLINE, x)
        self.window.addstr(self.row, self.label_col, " {} ".format(self._label), attrs)
项目:grbl-stream    作者:fragmuffin    | 项目源码 | 文件源码
def render(self, row):
        width = self.window.getmaxyx()[1]

        # Create List of render parameters
        render_list = [
            (0, '> ' if self._cur else '  ', 0),
        ]
        if isinstance(self.content, GCodeContent):
            render_list += self.content.to_render_list(2, max(0, width - 2))
        else:
            render_list += [(2, str(self.content), 0)]

        # Render content
        for (col, content, color_index) in render_list:
            if isinstance(content, int):
                # render individual character (usually one of curses.ACS_*)
                if col < width:
                    self.window.addch(
                        row, col, content,
                        curses.color_pair(color_index) if curses.has_colors() else 0
                    )

            else: # content is assumed to be a string
                ll = max(0, (width - 1) - col)  # line limit
                s = ("{:%i.%is}" % (ll, ll)).format(content).encode('utf-8') if ll else ''  # string
                if s:
                    self.window.addstr(
                        row, col, s,
                        curses.color_pair(color_index) if curses.has_colors() else 0
                    )
项目:sciibo    作者:fdev    | 项目源码 | 文件源码
def create_screen(fn):
    """
    Initializes curses and passes a Screen to the main loop function `fn`.
    Based on curses.wrapper.
    """
    try:
        # Make escape key more responsive
        os.environ['ESCDELAY'] = '25'

        stdscr = curses.initscr()

        curses.noecho()
        curses.cbreak()
        stdscr.keypad(1)
        stdscr.nodelay(1)
        curses.curs_set(0)

        curses.mousemask(curses.BUTTON1_CLICKED)

        if curses.has_colors():
            curses.start_color()
            curses.use_default_colors()

        screen = Screen(stdscr)
        fn(screen)

    finally:
        # Set everything back to normal
        if 'stdscr' in locals():
            curses.use_default_colors()
            curses.curs_set(1)
            stdscr.keypad(0)
            curses.echo()
            curses.nocbreak()
            curses.endwin()
项目:python2-tracer    作者:extremecoders-re    | 项目源码 | 文件源码
def set_color(win, color):
    if curses.has_colors():
        n = color + 1
        curses.init_pair(n, color, my_bg)
        win.attroff(curses.A_COLOR)
        win.attron(curses.color_pair(n))
项目:python2-tracer    作者:extremecoders-re    | 项目源码 | 文件源码
def unset_color(win):
    if curses.has_colors():
        win.attrset(curses.color_pair(0))
项目:python2-tracer    作者:extremecoders-re    | 项目源码 | 文件源码
def mkpanel(color, rows, cols, tly, tlx):
    win = curses.newwin(rows, cols, tly, tlx)
    pan = panel.new_panel(win)
    if curses.has_colors():
        if color == curses.COLOR_BLUE:
            fg = curses.COLOR_WHITE
        else:
            fg = curses.COLOR_BLACK
        bg = color
        curses.init_pair(color, fg, bg)
        win.bkgdset(ord(' '), curses.color_pair(color))
    else:
        win.bkgdset(ord(' '), curses.A_BOLD)

    return pan
项目:python2-tracer    作者:extremecoders-re    | 项目源码 | 文件源码
def next_j(j):
    if j == 0:
        j = 4
    else:
        j -= 1

    if curses.has_colors():
        z = randrange(0, 3)
        color = curses.color_pair(z)
        if z:
            color = color | curses.A_BOLD
        stdscr.attrset(color)

    return j
项目:solent    作者:solent-eng    | 项目源码 | 文件源码
def screen_curses_init():
    #
    # number of milliseconds to wait after reading an escape character, to
    # distinguish between an individual escape character entered on the
    # keyboard from escape sequences sent by cursor and function keys (see
    # curses(3X).
    os.putenv("ESCDELAY", "0") # was 25
    #
    global STDSCR
    STDSCR = curses.initscr()
    curses.noecho()
    curses.cbreak()
    #
    if not curses.has_colors():
        raise Exception("Need colour support to run.")
    curses.raw()
    #
    curses.start_color()
    #
    # This is what allows us to use -1 for default when we initialise
    # the pairs
    curses.use_default_colors()
    #
    curses.init_pair(PROFILE_GREY       , curses.COLOR_WHITE    , -1)
    curses.init_pair(PROFILE_WHITE      , curses.COLOR_WHITE    , -1)
    curses.init_pair(PROFILE_RED        , curses.COLOR_RED      , -1)
    curses.init_pair(PROFILE_VERMILION  , curses.COLOR_RED      , -1)
    curses.init_pair(PROFILE_ORANGE     , curses.COLOR_RED      , -1)
    curses.init_pair(PROFILE_AMBER      , curses.COLOR_YELLOW   , -1)
    curses.init_pair(PROFILE_YELLOW     , curses.COLOR_YELLOW   , -1)
    curses.init_pair(PROFILE_CHARTREUSE , curses.COLOR_GREEN    , -1)
    curses.init_pair(PROFILE_GREEN      , curses.COLOR_GREEN    , -1)
    curses.init_pair(PROFILE_TEAL       , curses.COLOR_CYAN     , -1)
    curses.init_pair(PROFILE_BLUE       , curses.COLOR_BLUE     , -1)
    curses.init_pair(PROFILE_VIOLET     , curses.COLOR_MAGENTA  , -1)
    curses.init_pair(PROFILE_PURPLE     , curses.COLOR_MAGENTA  , -1)
    curses.init_pair(PROFILE_MAGENTA    , curses.COLOR_MAGENTA  , -1)
    curses.init_pair(PROFILE_BLACK_INFO , curses.COLOR_BLACK    , curses.COLOR_WHITE)
    curses.init_pair(PROFILE_ALARM,       curses.COLOR_RED      , curses.COLOR_WHITE)
项目:Adwear    作者:Uberi    | 项目源码 | 文件源码
def _start(self):
        """
        Initialize the screen and input mode.
        """
        self.s = curses.initscr()
        self.has_color = curses.has_colors()
        if self.has_color:
            curses.start_color()
            if curses.COLORS < 8:
                # not colourful enough
                self.has_color = False
        if self.has_color:
            try:
                curses.use_default_colors()
                self.has_default_colors=True
            except _curses.error:
                self.has_default_colors=False
        self._setup_colour_pairs()
        curses.noecho()
        curses.meta(1)
        curses.halfdelay(10) # use set_input_timeouts to adjust
        self.s.keypad(0)

        if not self._signal_keys_set:
            self._old_signal_keys = self.tty_signal_keys()

        super(Screen, self)._start()
项目:loltanks    作者:whentze    | 项目源码 | 文件源码
def main(screen):
  screen.clear()
  screen.keypad(True)
  curses.curs_set(False)
  width = curses.COLS
  height = curses.LINES

  if(height < 20 or width < 50):
    raise RuntimeError("This terminal is too damn small!")

  if not (curses.has_colors()):
    raise RuntimeError("This terminal does not support colors!")

  if not (curses.can_change_color()):
    raise RuntimeError("This terminal does not support changing color definitions!")

  conf = configs.nice_conf
  menu.confmenu(conf, screen)

  screen.nodelay(True)
  screen.clear()
  screen.refresh()
  mainwin = curses.newwin(height-7, width, 0, 0)
  statuswin = curses.newwin(7, width, height-7, 0)

  while(1):
    world = World(mainwin, conf)
    activeplayer = 0
    n_turns = 1

    for p in itertools.cycle(world.players):
      if(p.isdead):
        continue
      world.wind = randint(max(-conf['wind_max'], world.wind-conf['wind_change']),
                           min( conf['wind_max'], world.wind+conf['wind_change']))
      p.isactive = True
      p.active_shots = 0
      while ((p.isactive or p.active_shots > 0) and not len([p for p in world.players if not p.isdead]) <= 1 ):
        gamestep(screen, mainwin, statuswin, p, world, conf, n_turns)
      if (len([p for p in world.players if not p.isdead]) == 1):
        gameover(screen, [p for p in world.players if not p.isdead][0])
        break
      if (len([p for p in world.players if not p.isdead]) == 0):
        gameover(screen, None)
        break
      n_turns += 1
项目:sandsifter    作者:xoreaxeaxeax    | 项目源码 | 文件源码
def init_colors(self):
        if curses.has_colors() and curses.can_change_color():
            curses.init_color(self.COLOR_BLACK, 0, 0, 0)
            curses.init_color(self.COLOR_WHITE, 1000, 1000, 1000)
            curses.init_color(self.COLOR_BLUE, 0, 0, 1000)
            curses.init_color(self.COLOR_RED, 1000, 0, 0)
            curses.init_color(self.COLOR_GREEN, 0, 1000, 0)

            # this will remove flicker, but gives boring colors
            '''
            self.COLOR_BLACK = curses.COLOR_BLACK
            self.COLOR_WHITE = curses.COLOR_WHITE
            self.COLOR_BLUE = curses.COLOR_BLUE
            self.COLOR_RED = curses.COLOR_RED
            self.COLOR_GREEN = curses.COLOR_GREEN
            '''

            for i in xrange(0, self.GRAYS):
                curses.init_color(
                        self.GRAY_BASE + i,
                        i * 1000 / (self.GRAYS - 1),
                        i * 1000 / (self.GRAYS - 1),
                        i * 1000 / (self.GRAYS - 1)
                        )
                curses.init_pair(
                        self.GRAY_BASE + i,
                        self.GRAY_BASE + i,
                        self.COLOR_BLACK
                        )

        else:
            self.COLOR_BLACK = curses.COLOR_BLACK
            self.COLOR_WHITE = curses.COLOR_WHITE
            self.COLOR_BLUE = curses.COLOR_BLUE
            self.COLOR_RED = curses.COLOR_RED
            self.COLOR_GREEN = curses.COLOR_GREEN

            for i in xrange(0, self.GRAYS):
                curses.init_pair(
                        self.GRAY_BASE + i,
                        self.COLOR_WHITE,
                        self.COLOR_BLACK
                        )

        curses.init_pair(self.BLACK, self.COLOR_BLACK, self.COLOR_BLACK)
        curses.init_pair(self.WHITE, self.COLOR_WHITE, self.COLOR_BLACK)
        curses.init_pair(self.BLUE, self.COLOR_BLUE, self.COLOR_BLACK)
        curses.init_pair(self.RED, self.COLOR_RED, self.COLOR_BLACK)
        curses.init_pair(self.GREEN, self.COLOR_GREEN, self.COLOR_BLACK)
项目:python2-tracer    作者:extremecoders-re    | 项目源码 | 文件源码
def dline(pair, from_x, from_y, x2, y2, ch):
    if curses.has_colors():
        stdscr.attrset(curses.color_pair(pair))

    dx = x2 - from_x
    dy = y2 - from_y

    ax = abs(dx * 2)
    ay = abs(dy * 2)

    sx = sign(dx)
    sy = sign(dy)

    x = from_x
    y = from_y

    if ax > ay:
        d = ay - ax // 2

        while True:
            plot(x, y, ch)
            if x == x2:
                return

            if d >= 0:
                y += sy
                d -= ax
            x += sx
            d += ay
    else:
        d = ax - ay // 2

        while True:
            plot(x, y, ch)
            if y == y2:
                return

            if d >= 0:
                x += sx
                d -= ay
            y += sy
            d += ax
项目:ci_edit    作者:google    | 项目源码 | 文件源码
def __init__(self, cursesScreen):
    self.clicks = 0
    self.debugMouseEvent = (0, 0, 0, 0, 0)
    self.exiting = False
    self.modalUi = None
    self.modeStack = []
    self.priorClick = 0
    self.savedMouseButton1Down = False
    self.savedMouseWindow = None
    self.savedMouseX = -1
    self.savedMouseY = -1
    self.cursesScreen = cursesScreen
    self.ch = 0
    curses.mousemask(-1)
    curses.mouseinterval(0)
    # Enable mouse tracking in xterm.
    sys.stdout.write('\033[?1002;h\n')
    #sys.stdout.write('\033[?1005;h\n')
    curses.meta(1)
    # Access ^c before shell does.
    curses.raw()
    # Enable Bracketed Paste Mode.
    sys.stdout.write('\033[?2004;h\n')
    #curses.start_color()
    curses.use_default_colors()
    if 0:
      assert(curses.COLORS == 256)
      assert(curses.can_change_color() == 1)
      assert(curses.has_colors() == 1)
      app.log.detail("color_content:")
      for i in range(0, curses.COLORS):
        app.log.detail("color", i, ": ", curses.color_content(i))
      for i in range(16, curses.COLORS):
        curses.init_color(i, 500, 500, i * 787 % 1000)
      app.log.detail("color_content, after:")
      for i in range(0, curses.COLORS):
        app.log.detail("color", i, ": ", curses.color_content(i))
    self.setUpPalette()
    if 1:
      #rows, cols = self.cursesScreen.getmaxyx()
      cursesWindow = self.cursesScreen
      cursesWindow.leaveok(1)  # Don't update cursor position.
      cursesWindow.scrollok(0)
      cursesWindow.timeout(10)
      cursesWindow.keypad(1)
      self.top, self.left = cursesWindow.getyx()
      self.rows, self.cols = cursesWindow.getmaxyx()
      app.window.mainCursesWindow = cursesWindow
    self.zOrder = []