7

如何使用 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"

显示:

你好!

^[[0m^[[30;47m你好!^[[0m

最终,我需要颜色:

如何在 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
4

1 回答 1

10

ruby 源代码中有 curses 用法的示例,请参见此处

您的代码可能类似于:

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
于 2011-09-07T09:35:15.887 回答