2011-09-07 58 views
5

如何使用Ruby的默認Curses庫獲取顏色?Ruby curses顏色

因此,像:

puts "\e[0m\e[30;47mtest\e[0m" 

的偉大工程。在淺灰色背景上呈現出漂亮的黑色。但這:

#!/usr/bin/env ruby 

require 'curses' 

Curses.noecho # do not show typed keys 
Curses.init_screen 
Curses.stdscr.keypad(true) # enable arrow keys (for pageup/down) 
Curses.stdscr.nodelay = 1 

Curses.clear 
Curses.setpos(0,0) 
Curses.addstr "Hello!" 
Curses.addstr "\e[0m\e[30;47mHello!\e[0m" 

顯示:

您好!

^[0米^ [[30; 47mHello^[0米

最後,我需要的顏色爲這個!

How to capture a key press in Ruby?

require 'curses' 

Curses.noecho # do not show typed keys 
Curses.init_screen 
Curses.stdscr.keypad(true) # enable arrow keys (required for pageup/down) 

loop do 
    case Curses.getch 
    when Curses::Key::PPAGE 
    Curses.setpos(0,0) 
    Curses.addstr("Page Up") 
    when Curses::Key::NPAGE 
    Curses.setpos(0,0) 
    Curses.addstr("Page Dn") 
    end 
end 
+1

僅供參考'從STDLIB已經過時curses',應儘量'ncurses' - https://github.com/eclubb/ncurses-ruby/具有適當的文檔 – basicxman

+1

@basicxman,是什麼讓你說stdlib的curses已被棄用? – cam

+0

libruby'curses'確實沒有適當的文檔,我只能在SO –

回答

9

有詛咒的例子在ruby源代碼中的用法,請參閱,例如here

你的代碼可能是這樣的:

require 'curses' 
include Curses 

Curses.noecho # do not show typed keys 
Curses.init_screen 
Curses.stdscr.keypad(true) # enable arrow keys (required for pageup/down) 
Curses.start_color 
# Determines the colors in the 'attron' below 
Curses.init_pair(COLOR_BLUE,COLOR_BLUE,COLOR_BLACK) 
Curses.init_pair(COLOR_RED,COLOR_RED,COLOR_BLACK) 

loop do 

    case Curses.getch 

    when Curses::Key::PPAGE 
    Curses.clear 
    Curses.setpos(0,0) 
    # Use colors defined color_init 
    Curses.attron(color_pair(COLOR_RED)|A_NORMAL){ 
     Curses.addstr("Page Up") 
    } 
    when Curses::Key::NPAGE 
    Curses.clear 
    Curses.setpos(0,0) 
    Curses.attron(color_pair(COLOR_BLUE)|A_NORMAL){ 
     Curses.addstr("Page Down") 
    } 
    end 
end