Example #1
0
def init_colors():
    """
    Modify and then initialize color pairs to match an actual Rubiks cube.
    """
    colors = {
        20: 'C41E3A',  # red
        21: '0051BA',  # green
        22: '009E60',  # blue
        23: 'FFD500',  # yellow
        24: 'FF5800',  # orange
    }
    old_colors = {}
    for key, value in colors.items():
        old_colors[key] = curses.color_content(key)
        logging.info('Old color: {} - {}'.format(key, old_colors))
        r = int(value[0:2], 16) / 255 * 1000
        g = int(value[2:4], 16) / 255 * 1000
        b = int(value[4:6], 16) / 255 * 1000
        curses.init_color(key, int(r), int(g), int(b))
        logging.info('New color: {} - {}'.format(key, curses.color_content(key)))

    curses.init_pair(1, 20, -1)  # red
    curses.init_pair(2, 21, -1)  # green
    curses.init_pair(3, 22, -1)  # blue
    curses.init_pair(4, curses.COLOR_WHITE, -1)  # white
    curses.init_pair(5, 23, -1)  # yellow
    curses.init_pair(6, 24, -1)  # orange

    return old_colors
Example #2
0
def ncurses_color_to_html(color):
    """
    Takes an int between 0 and 256 and returns
    a string of the form #XXXXXX representing an
    html color.
    """
    if color <= 15:
        try:
            (r, g, b) = curses.color_content(color)
        except: # fallback in faulty terminals (e.g. xterm)
            (r, g, b) = curses.color_content(color%8)
        r = r / 1000 * 6 - 0.01
        g = g / 1000 * 6 - 0.01
        b = b / 1000 * 6 - 0.01
    elif color <= 231:
        color = color - 16
        r = color % 6
        color = color / 6
        g = color % 6
        color = color / 6
        b = color % 6
    else:
        color -= 232
        r = g = b = color / 24 * 6
    return '#%02X%02X%02X' % (r*256/6, g*256/6, b*256/6)
Example #3
0
def curses_status( ca, args ):
    ca.stdscr.addstr(
        "Baudrate      : %s\n" % curses.baudrate() )
    ca.stdscr.addstr(
        "Has color     : %s\n" % curses.has_colors() )
    ca.stdscr.addstr(
        "Change color  : %s\n" % curses.can_change_color() )
    ca.stdscr.addstr(
        "Insert char   : %s\n" % curses.has_ic() )
    ca.stdscr.addstr(
        "Insert line   : %s\n" % curses.has_il() )
    ca.stdscr.addstr(
        "Color numbers : 0-%s\n" % curses.COLORS )
    ca.stdscr.addstr(
        "COLOR_WHITE   : %s\n" % (curses.color_content(curses.COLOR_WHITE),) )
    ca.stdscr.addstr(
        "COLOR_BLACK   : %s\n" % (curses.color_content(curses.COLOR_BLACK),) )
    ca.stdscr.addstr(
        "COLOR_RED     : %s\n" % (curses.color_content(curses.COLOR_RED),) )
    ca.stdscr.addstr(
        "COLOR_GREEN   : %s\n" % (curses.color_content(curses.COLOR_GREEN),) )
    ca.stdscr.addstr(
        "COLOR_BLUE    : %s\n" % (curses.color_content(curses.COLOR_BLUE),) )
    ca.stdscr.addstr(
        "COLOR_YELLOW  : %s\n" % (curses.color_content(curses.COLOR_YELLOW),) )
    ca.stdscr.addstr(
        "COLOR_MAGENTA : %s\n" % (curses.color_content(curses.COLOR_MAGENTA),))
    ca.stdscr.addstr(
        "COLOR_CYAN    : %s\n" % (curses.color_content(curses.COLOR_CYAN),) )
    ca.stdscr.addstr(
        "Erase char    : %s\n" % (curses.erasechar(),) )

    ls = list( filter( lambda x: curses.has_key(x), range(255) ))
    ca.stdscr.addstr(
        "Unknown keys  : %s\n" % ls )
Example #4
0
def main(stdscr):
    stdscr.clear()
    curses.start_color()
    curses.use_default_colors()
    curses.init_pair(2,curses.COLOR_WHITE,-1) #set white to term default

    curses.init_pair(1,curses.COLOR_BLACK, curses.COLOR_CYAN)
    curses.init_pair(2,curses.COLOR_BLACK, curses.COLOR_WHITE)
   
    #paint 20 rows, 60 columns cyan
    i = 0
    while i < 20:
        j = 0
        while j < 60:
            stdscr.addstr(i,j," ",curses.color_pair(1))
            j += 1
        i += 1
    stdscr.refresh()
   
    #make 2nd window
    height = 5
    width = 40
    secondWindow = curses.newwin(height, width,5,5)

    #display color content
    x,y,z = curses.color_content(curses.COLOR_WHITE)
    secondWindow.addstr(0,3,"Color content of COLOR_WHITE:")
    secondWindow.addstr(1,3,str(x))
    secondWindow.addstr(2,3,str(y))
    secondWindow.addstr(3,3,str(z))
    secondWindow.addstr(4,3,"Not same as default white")
    secondWindow.refresh()
   
    stdscr.getch()
Example #5
0
def display_info(stdscr):
    display_info_line(stdscr, "COLS: {}".format(curses.COLS))
    display_info_line(stdscr, "LINES: {}".format(curses.LINES))
    display_info_line(stdscr, "Bold", curses.color_pair(0) | curses.A_BOLD)
    display_info_line(stdscr, "Blink", curses.A_BLINK)
    display_info_line(stdscr, "Blink + Standout", curses.A_BLINK | curses.A_STANDOUT)
    display_info_line(stdscr, "Stand out", curses.A_STANDOUT)
    display_info_line(stdscr, "Dim", curses.A_DIM)
    display_info_line(stdscr, "Underline", curses.A_UNDERLINE)
    display_info_line(stdscr, "Normal", curses.A_NORMAL)
    display_info_line(stdscr, "Reverse", curses.A_REVERSE)
    display_info_line(stdscr, "Color", curses.A_COLOR)
    display_info_line(stdscr, "Chartext", curses.A_CHARTEXT)
    display_info_line(stdscr, "Low", curses.A_LOW)
    display_info_line(stdscr, "Left", curses.A_LEFT)
    display_info_line(stdscr, "Can change color pair: %s" % curses.can_change_color())
    display_info_line(stdscr, "Color pairs: %s" % curses.COLOR_PAIRS)
    display_info_line(stdscr, "# of colors: %d" % curses.COLORS)

    if curses.can_change_color():
        display_info_line(stdscr, "The terminal should show a green gradient below. If it's colorful instead, curses can't change terminal color.")
        matrix.init_colors()
        for i in range(matrix.NUMBER_OF_COLOR):
            color_num = matrix.START_COLOR_NUM + i
            display_info_line(stdscr, "Pair {} {} {}".format(color_num, curses.color_content(color_num), curses.pair_content(color_num)), curses.color_pair(color_num))

    stdscr.getch()
Example #6
0
def safescrtest():
    with safescreen('xterm-256color') as scr:
        for colnum in range(curses.COLORS):
            r,g,b = colors256[colnum]
            val = r + g + b
            if val < (16**2)*3 *.6:
                curses.init_pair(colnum, 15, colnum)
            else:
                curses.init_pair(colnum, 0, colnum)
        
        for colnum in range(0,16):
            r,g,b = colors256[colnum]
            rgbhex = "%02x%02x%02x" % (r,g,b)
            r2,g2,b2 = curses.color_content(colnum)
            r2 = r2*255 / 1000
            g2 = g2*255 / 1000
            b2 = b2*255 / 1000
            rgbhex2 = "%02x%02x%02x" % (r2,g2,b2)
            val = r + g + b
            scr.addstr(rgbhex + ' ', curses.color_pair(colnum))
            scr.addstr(rgbhex2, curses.color_pair(colnum))
            if (colnum + 1) % 4 == 0:
                scr.addstr('\n')
            
            
        for colnum in range(16,curses.COLORS):
            r,g,b = colors256[colnum]
            rgbhex = "%02x%02x%02x" % (r,g,b)
            
            scr.addstr(rgbhex, curses.color_pair(colnum))
            if colnum >= 232 and (colnum + 1) % 8 == 0:
                scr.addstr('\n')
            elif 16 <= colnum < 232 and (colnum +3) % 6 == 0:
                scr.addstr('\n')
        scr.getch()
Example #7
0
File: display.py Project: Josca/im
 def _define_color(self, i_color: int, r: int, g: int, b: int):
     key = (r, g, b)
     old_rgb = curses.color_content(i_color)
     self.colors[key] = (i_color, old_rgb)
     r = int(1000 * r / 255)
     g = int(1000 * g / 255)
     b = int(1000 * b / 255)
     curses.init_color(i_color, r, g, b)
Example #8
0
    def __init__(self, *args, **kw):
        super().__init__(*args, **kw)

        # it's pretty clear that curses is usually on crack about what
        # it's returning, but OH WELL
        self.saved = [curses.color_content(i) for i in range(curses.COLORS)]

        self.reset()
Example #9
0
 def init_color_map(self):
     self._curses_color_map = {}
     for color_number in Console.curses_colors:
         r, g, b = curses.color_content(color_number)
         r = r * 255.0 / 1000
         g = g * 255.0 / 1000
         b = b * 255.0 / 1000
         color = Color(r, g, b)
         self._curses_color_map[color_number] = color
         curses.init_pair(color_number+1, color_number, curses.COLOR_BLACK)
Example #10
0
def main():
    stdscr = curses.initscr()   # MANDATORY!
    curses.start_color()        # MANDATORY!
    curses.use_default_colors() # optional.

    stdscr.addstr("can_change_color(): " + str(curses.can_change_color()) + '\n')
    stdscr.addstr("COLOR_PAIRS: " + str(curses.COLOR_PAIRS) + '\n\n')

    ####################################

    stdscr.addstr("color 67 before:\n")
    curses.init_pair(20, 67, 0)
    stdscr.addstr(str(curses.color_content(67)) + '\n', curses.color_pair(20))

    stdscr.addstr("color 67 after:\n")
    curses.init_color(67, 0, 255, 0)
    curses.init_pair(21, 67, 0)
    stdscr.addstr(str(curses.color_content(67)) + '\n\n', curses.color_pair(21))

    ####################################

    stdscr.addstr("color 101 before:\n")
    curses.init_pair(22, 101, 0)
    stdscr.addstr(str(curses.color_content(101)) + '\n', curses.color_pair(22))

    stdscr.addstr("color 101 after:\n")
    curses.init_color(101, 128, 128, 128)
    curses.init_pair(23, 101, 0)
    stdscr.addstr(str(curses.color_content(101)) + '\n\n', curses.color_pair(23))

    ####################################

    stdscr.addstr("pair 40 before:\n")
    stdscr.addstr(str(curses.pair_content(40)) + '\n', curses.color_pair(40))

    stdscr.addstr("pair 40 after:\n")
    curses.init_pair(40, 101, 67)
    stdscr.addstr(str(curses.pair_content(40)) + '\n\n', curses.color_pair(40))

    stdscr.getch()

    curses.endwin()     # optional, but recommended.
Example #11
0
def ncurses_color_to_rgb(color: int) -> Tuple[float, float, float]:
    if color <= 15:
        try:
            (r, g, b) = curses.color_content(color)
        except:  # fallback in faulty terminals (e.g. xterm)
            (r, g, b) = curses.color_content(color % 8)
        r = r / 1000 * 5
        g = g / 1000 * 5
        b = b / 1000 * 5
    elif color <= 231:
        color = color - 16
        b = color % 6
        color = color // 6
        g = color % 6
        color = color // 6
        r = color % 6
    else:
        color -= 232
        r = g = b = color / 24 * 5
    return r / 5, g / 5, b / 5
Example #12
0
def main(stdscr):
    stdscr.clear()
    curses.use_default_colors()
    #curses.init_color(1,400,0,0)
    if curses.has_colors():
        for i in xrange(1, curses.COLORS):
            curses.init_pair(i, i, curses.COLOR_BLACK)
            stdscr.addstr(str(curses.color_content(i))+"COLOR %d! " % i, curses.color_pair(i))
            stdscr.addstr(str(curses.can_change_color())+"BOLD! ", curses.color_pair(i) | curses.A_BOLD)
            stdscr.addstr("STANDOUT! ", curses.color_pair(i) | curses.A_STANDOUT)
            stdscr.addstr("UNDERLINE! ", curses.color_pair(i) | curses.A_UNDERLINE)
            stdscr.addstr("BLINK! ", curses.color_pair(i) | curses.A_BLINK)
            stdscr.addstr("DIM! ", curses.color_pair(i) | curses.A_DIM)
            stdscr.addstr("REVERSE! ", curses.color_pair(i) | curses.A_REVERSE)
    stdscr.refresh()
    stdscr.getch()
Example #13
0
 def __init__(self):
     self.Running = True
     self.stdscr = curses.initscr()
     curses.noecho()
     curses.start_color()
     self.origmodes = []
     if True:  # curses.can_change_color():## Debug _ True:
         for i in range(1, 6):
             self.origmodes.append(curses.color_content(i))
         curses.init_color(1, 0, 150, 0)
         curses.init_color(2, 0, 350, 0)
         curses.init_color(3, 0, 500, 0)
         curses.init_color(4, 0, 680, 0)
         curses.init_color(5, 0, 999, 0)
     self.initPairs()
     self.height, self.width = self.stdscr.getmaxyx()
     self.stdscr.refresh()
Example #14
0
def main():
    with vipad.safescreen('xterm-256color') as scr:
        #curses.init_colors()
        curses.use_default_colors()
        maxy, maxx = scr.getmaxyx()
        ncols, nlines = maxx,maxy-8
        uly, ulx = 4, 1
        
        #scr.addstr(uly-2, ulx, "Use Ctrl-G to end editing.")
        win = curses.newwin(nlines, ncols, uly, ulx)
        colset = dict()
        for i in range(curses.COLORS):
            curses.init_pair(i, i, -1)
            curses.init_pair(256+i, -1, i)
                
        #textpad.rectangle(scr, uly-1, ulx-1, uly + nlines, ulx + ncols)
        scr.refresh()
        textbox = vipad.Panelastext(win)
        #tb = basictester()
        tb = []
        test_textbox(textbox, tb)
        
        win.refresh()
        win.getch()
        win.erase()
        for i in range(curses.COLORS):
            rgb = curses.color_content(i)
            if rgb not in colset:
                colset[rgb] = i
            win.addstr(' ', curses.color_pair(256+i))
            if i == 15 or i == 255-24:
                win.addstr('\n')
                
        win.addstr('\n')
        win.refresh()
        win.getch()
    
    for rgb, col in sorted(colset.items()):
        print col, rgb
    print len(colset)
Example #15
0
def set_color(color_id, r, g, b):
    global old_colors

    old_colors[color_id] = curses.color_content(color_id)
    curses.init_color(color_id, r, g, b)
Example #16
0
#
Example #17
0
def main():
    stdscr = curses.initscr()
    curses.noecho()
    curses.nonl()
    curses.raw()
    colors = curses.has_colors()
    curses.start_color()
    if colors:
        curses.use_default_colors()
    stdscr.keypad(1)
    stdscr.scrollok(1)

    maxy, maxx = stdscr.getmaxyx()

    stdscr.attrset(curses.A_REVERSE)
    stdscr.addstr('‡\n')
    stdscr.attrset(0)
    x = stdscr.inch(0, 0)
    stdscr.move(2, 0)
    stdscr.addstr('inch(0,0) = %s; A_UNDERLINE=%d\n' % (repr(x), curses.A_UNDERLINE))

    stdscr.addstr(
        'COLORS=%d COLOR_PAIRS=%d has_colors()=%s can_change_color()=%s\n' % (
            curses.COLORS, curses.COLOR_PAIRS, colors, curses.can_change_color()))
    stdscr.addstr('%d\n' % (maxx,))
    rgbs=[]
    if colors:
        for i in range(curses.COLORS):
            rgb = '%02x%02x%02x' % tuple(int((j/1000)*255.0) for j in  curses.color_content(i))
            rgbs.append(rgb)
            stdscr.addstr(' %s' % (rgb,))
            if (stdscr.getyx()[1] + 7) > maxx:
                stdscr.addstr('\n')o
    stdscr.addstr('\n')
    stdscr.addstr('press a key')
    stdscr.get_wch()
    stdscr.addstr('\n')

    pairs = {}
    if colors:
        for i in range(min(curses.COLORS, curses.COLOR_PAIRS - 1)):
            curses.init_pair(i+1, -1, i)

        ## if curses.can_change_color():
        ##     for i in range(curses.COLORS):
        ##         curses.init_color(i, 0, 1000, 0)

    for i in range(1, curses.COLOR_PAIRS):
        #stdscr.addstr(' %03d' % (i,), curses.color_pair(i))
        stdscr.addstr(' %s' % (rgbs[i-1],), curses.color_pair(i))
        y, x = stdscr.getyx()
        if x + 7 > maxx:
            stdscr.addstr('\n')
    else:
        stdscr.addstr('\n')

    stdscr.addstr('press a key')
    stdscr.get_wch()
    stdscr.addstr('\n')
    if colors:
        if curses.can_change_color():
            for i in range(curses.COLORS):
                curses.init_color(i, 0, 1000, 0)

    stdscr.addstr('press q to quit\n')

    x = None
    while x != 'q':
        x = stdscr.get_wch()
        stdscr.addstr('%s %s %s %s\n' % (
            type(x),
            repr(x),
            repr(x) if isinstance(x, str) else curses.keyname(x),
            repr(x) if isinstance(x, str) else unkey.get(x, '???'),
            ))
        if x == curses.KEY_RESIZE:
            maxy, maxx = stdscr.getmaxyx()
            stdscr.addstr('Resize! %d %d\n' % (maxy, maxx))

    curses.noraw()
    curses.nl()
    curses.echo()
    curses.endwin()
Example #18
0
def init_colour(color_bg, color_fg):
    """
  Based on `human_ui.CursesUi._init_colour`
  (https://github.com/deepmind/pycolab/blob/master/pycolab/human_ui.py)
  """
    curses.start_color()
    # The default colour for all characters without colours listed is boring
    # white on black, or "system default", or somesuch.
    colour_pair = collections.defaultdict(lambda: 0)
    # And if the terminal doesn't support true color, that's all you get.
    if not curses.can_change_color():
        return colour_pair

    # Collect all unique foreground and background colours. If this terminal
    # doesn't have enough colours for all of the colours the user has supplied,
    # plus the two default colours, plus the largest colour id (which we seem
    # not to be able to assign, at least not with xterm-256color) stick with
    # boring old white on black.
    colours = set(six.itervalues(color_fg)).union(six.itervalues(color_bg))
    if (curses.COLORS - 2) < len(colours):
        return colour_pair

    # Get all unique characters that have a foreground and/or background colour.
    # If this terminal doesn't have enough colour pairs for all characters plus
    # the default colour pair, stick with boring old white on black.
    characters = set(color_fg).union(color_bg)
    if (curses.COLOR_PAIRS - 1) < len(characters):
        return colour_pair

    # Get the identifiers for both colours in the default colour pair.
    cpair_0_fg_id, cpair_0_bg_id = curses.pair_content(0)

    # With all this, make a mapping from colours to the IDs we'll use for them.
    ids = set(
        range(curses.COLORS - 1)
    ) - {  # The largest ID is not assignable?
        cpair_0_fg_id,
        cpair_0_bg_id,
    }  # We don't want to change these.
    ids = list(reversed(sorted(ids)))  # We use colour IDs from large to small.
    ids = ids[:len(colours)]  # But only those colour IDs we actually need.
    colour_ids = dict(zip(colours, ids))

    # Program these colours into curses.
    for colour, cid in six.iteritems(colour_ids):
        curses.init_color(cid, *colour)

    # Now add the default colours to the colour-to-ID map.
    cpair_0_fg = curses.color_content(cpair_0_fg_id)
    cpair_0_bg = curses.color_content(cpair_0_bg_id)
    colour_ids[cpair_0_fg] = cpair_0_fg_id
    colour_ids[cpair_0_bg] = cpair_0_bg_id

    # The color pair IDs we'll use for all characters count up from 1; note that
    # the "default" colour pair of 0 is already defined, since _colour_pair is a
    # defaultdict.
    colour_pair.update(
        {character: pid
         for pid, character in enumerate(characters, start=1)})

    # Program these color pairs into curses, and that's all there is to do.
    for character, pid in six.iteritems(colour_pair):
        # Get foreground and background colours for this character. Note how in
        # the absence of a specified background colour, the same colour as the
        # foreground is used.
        cpair_fg = color_fg.get(character, cpair_0_fg_id)
        cpair_bg = color_bg.get(character, cpair_fg)
        # Get colour IDs for those colours and initialise a colour pair.
        cpair_fg_id = colour_ids[cpair_fg]
        cpair_bg_id = colour_ids[cpair_bg]
        curses.init_pair(pid, cpair_fg_id, cpair_bg_id)

    return colour_pair
Example #19
0
def module_funcs(stdscr):
    "Test module-level functions"

    for func in [curses.baudrate, curses.beep, curses.can_change_color,
                 curses.cbreak, curses.def_prog_mode, curses.doupdate,
                 curses.filter, curses.flash, curses.flushinp,
                 curses.has_colors, curses.has_ic, curses.has_il,
                 curses.isendwin, curses.killchar, curses.longname,
                 curses.nocbreak, curses.noecho, curses.nonl,
                 curses.noqiflush, curses.noraw,
                 curses.reset_prog_mode, curses.termattrs,
                 curses.termname, curses.erasechar, curses.getsyx]:
        func()

    # Functions that actually need arguments
    if curses.tigetstr("cnorm"):
        curses.curs_set(1)
    curses.delay_output(1)
    curses.echo() ; curses.echo(1)

    f = tempfile.TemporaryFile()
    stdscr.putwin(f)
    f.seek(0)
    curses.getwin(f)
    f.close()

    curses.halfdelay(1)
    curses.intrflush(1)
    curses.meta(1)
    curses.napms(100)
    curses.newpad(50,50)
    win = curses.newwin(5,5)
    win = curses.newwin(5,5, 1,1)
    curses.nl() ; curses.nl(1)
    curses.putp('abc')
    curses.qiflush()
    curses.raw() ; curses.raw(1)
    curses.setsyx(5,5)
    curses.tigetflag('hc')
    curses.tigetnum('co')
    curses.tigetstr('cr')
    curses.tparm('cr')
    curses.typeahead(sys.__stdin__.fileno())
    curses.unctrl('a')
    curses.ungetch('a')
    curses.use_env(1)

    # Functions only available on a few platforms
    if curses.has_colors():
        curses.start_color()
        curses.init_pair(2, 1,1)
        curses.color_content(1)
        curses.color_pair(2)
        curses.pair_content(curses.COLOR_PAIRS - 1)
        curses.pair_number(0)

        if hasattr(curses, 'use_default_colors'):
            curses.use_default_colors()

    if hasattr(curses, 'keyname'):
        curses.keyname(13)

    if hasattr(curses, 'has_key'):
        curses.has_key(13)

    if hasattr(curses, 'getmouse'):
        (availmask, oldmask) = curses.mousemask(curses.BUTTON1_PRESSED)
        # availmask indicates that mouse stuff not available.
        if availmask != 0:
            curses.mouseinterval(10)
            # just verify these don't cause errors
            m = curses.getmouse()
            curses.ungetmouse(*m)

    if hasattr(curses, 'is_term_resized'):
        curses.is_term_resized(*stdscr.getmaxyx())
    if hasattr(curses, 'resizeterm'):
        curses.resizeterm(*stdscr.getmaxyx())
    if hasattr(curses, 'resize_term'):
        curses.resize_term(*stdscr.getmaxyx())
Example #20
0
    def _init_colour(self):
        """Allocate curses colours and "colour pairs" for user-specified colours.

    Curses manages colour in the following way: first, entries within a
    finite palette of colours (usually 255) are assigned a particular RGB value;
    next, foreground and background pairs of these colours are defined in a
    second palette of colour pairs (also finite; perhaps around 32767 entries).
    This function takes the `colour_fg` and `colour_bg` dicts supplied to the
    constructor and attempts to allocate enough colours and colour pairs to
    handle all of the colour combinations that they specify.

    If this method determines that the terminal isn't capable of accepting a
    custom colour palette, or if there turn out not to be enough colours or
    colour pairs to accommodate the user-supplied colour dicts, this method will
    simply allow the default foreground and background colour to be used.
    """
        # The default colour for all characters without colours listed is boring
        # white on black, or "system default", or somesuch.
        self._colour_pair = collections.defaultdict(lambda: 0)
        # And if the terminal doesn't support true color, that's all you get.
        if not curses.can_change_color(): return

        # Collect all unique foreground and background colours. If this terminal
        # doesn't have enough colours for all of the colours the user has supplied,
        # plus the two default colours, plus the largest colour id (which we seem
        # not to be able to assign, at least not with xterm-256color) stick with
        # boring old white on black.
        colours = set(six.itervalues(self._colour_fg)).union(
            six.itervalues(self._colour_bg))
        if (curses.COLORS - 2) < len(colours): return

        # Get all unique characters that have a foreground and/or background colour.
        # If this terminal doesn't have enough colour pairs for all characters plus
        # the default colour pair, stick with boring old white on black.
        characters = set(self._colour_fg).union(self._colour_bg)
        if (curses.COLOR_PAIRS - 1) < len(characters): return

        # Get the identifiers for both colours in the default colour pair.
        cpair_0_fg_id, cpair_0_bg_id = curses.pair_content(0)

        # With all this, make a mapping from colours to the IDs we'll use for them.
        ids = (
            set(range(curses.COLORS - 1))
            -  # The largest ID is not assignable?
            {cpair_0_fg_id, cpair_0_bg_id})  # We don't want to change these.
        ids = list(reversed(
            sorted(ids)))  # We use colour IDs from large to small.
        ids = ids[:len(colours)]  # But only those colour IDs we actually need.
        colour_ids = dict(zip(colours, ids))

        # Program these colours into curses.
        for colour, cid in six.iteritems(colour_ids):
            curses.init_color(cid, *colour)

        # Now add the default colours to the colour-to-ID map.
        cpair_0_fg = curses.color_content(cpair_0_fg_id)
        cpair_0_bg = curses.color_content(cpair_0_bg_id)
        colour_ids[cpair_0_fg] = cpair_0_fg_id
        colour_ids[cpair_0_bg] = cpair_0_bg_id

        # The color pair IDs we'll use for all characters count up from 1; note that
        # the "default" colour pair of 0 is already defined, since _colour_pair is a
        # defaultdict.
        self._colour_pair.update({
            character: pid
            for pid, character in enumerate(characters, start=1)
        })

        # Program these color pairs into curses, and that's all there is to do.
        for character, pid in six.iteritems(self._colour_pair):
            # Get foreground and background colours for this character. Note how in
            # the absence of a specified background colour, the same colour as the
            # foreground is used.
            cpair_fg = self._colour_fg.get(character, cpair_0_fg_id)
            cpair_bg = self._colour_bg.get(character, cpair_fg)
            # Get colour IDs for those colours and initialise a colour pair.
            cpair_fg_id = colour_ids[cpair_fg]
            cpair_bg_id = colour_ids[cpair_bg]
            curses.init_pair(pid, cpair_fg_id, cpair_bg_id)
Example #21
0
import random
import curses

#Initialize Screen
s = curses.initscr()
curses.start_color()
curses.curs_set(0)

curses.color_content(10)
sh, sw = s.getmaxyx()
#creating window
win = curses.newwin(sh, sw, 0, 0)
curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_BLUE)
win.bkgd(' ', curses.color_pair(1) | curses.A_BOLD)
#keypad Input
win.keypad(1)
win.timeout(100)  #refresh screen

#snake starting codinates
snake_x = sw // 4
snake_y = sh // 2

#snake bodyPart
snake = [[snake_y, snake_x], [snake_y, snake_x - 1], [snake_y, snake_x - 2]]

#food
food = [sh // 2, sw // 2]
win.addch(food[0], food[1], curses.ACS_BLOCK)

#Initial Direction
key = curses.KEY_RIGHT
Example #22
0
def module_funcs(stdscr):
    "Test module-level functions"

    for func in [curses.baudrate, curses.beep, curses.can_change_color,
                 curses.cbreak, curses.def_prog_mode, curses.doupdate,
                 curses.filter, curses.flash, curses.flushinp,
                 curses.has_colors, curses.has_ic, curses.has_il,
                 curses.isendwin, curses.killchar, curses.longname,
                 curses.nocbreak, curses.noecho, curses.nonl,
                 curses.noqiflush, curses.noraw,
                 curses.reset_prog_mode, curses.termattrs,
                 curses.termname, curses.erasechar, curses.getsyx]:
        func()

    # Functions that actually need arguments
    if curses.tigetstr("cnorm"):
        curses.curs_set(1)
    curses.delay_output(1)
    curses.echo() ; curses.echo(1)

    f = tempfile.TemporaryFile()
    stdscr.putwin(f)
    f.seek(0)
    curses.getwin(f)
    f.close()

    curses.halfdelay(1)
    curses.intrflush(1)
    curses.meta(1)
    curses.napms(100)
    curses.newpad(50,50)
    win = curses.newwin(5,5)
    win = curses.newwin(5,5, 1,1)
    curses.nl() ; curses.nl(1)
    curses.putp('abc')
    curses.qiflush()
    curses.raw() ; curses.raw(1)
    curses.setsyx(5,5)
    curses.tigetflag('hc')
    curses.tigetnum('co')
    curses.tigetstr('cr')
    curses.tparm('cr')
    curses.typeahead(sys.__stdin__.fileno())
    curses.unctrl('a')
    curses.ungetch('a')
    curses.use_env(1)

    # Functions only available on a few platforms
    if curses.has_colors():
        curses.start_color()
        curses.init_pair(2, 1,1)
        curses.color_content(1)
        curses.color_pair(2)
        curses.pair_content(curses.COLOR_PAIRS - 1)
        curses.pair_number(0)

        if hasattr(curses, 'use_default_colors'):
            curses.use_default_colors()

    if hasattr(curses, 'keyname'):
        curses.keyname(13)

    if hasattr(curses, 'has_key'):
        curses.has_key(13)

    if hasattr(curses, 'getmouse'):
        (availmask, oldmask) = curses.mousemask(curses.BUTTON1_PRESSED)
        # availmask indicates that mouse stuff not available.
        if availmask != 0:
            curses.mouseinterval(10)
            # just verify these don't cause errors
            m = curses.getmouse()
            curses.ungetmouse(*m)
Example #23
0
#