curses 라이브러리 간단한 정리

Ruby에서의 curses 라이브러리가 windows XP의 command 창에서도 동작하길래 몇가지 명령어만 간단히 정리해 봅니다.

기본 형식

init_screen으로 실행하고 ensure 문을 사용해서 반드시 close_screen이 호출되도록 한다
require 'curses'
include Curses

init_screen
begin
    # 실행코드
ensure
    close_screen
end

커서 관련

setpos 함수로 커서 위치 지정하고 curs_set 함수로 커서를 보이게 하거나 감춘다

화면 입출력

출력은 addstr 함수, 한글자 입력은 getch, 문자열 입력은 getstr 함수
사용자 입력을 보이지 않게 하려면 noecho 함수 호출
사용자가 enter 입력할 때까지 line buffer 방식으로 입력받으면 nocbreak 함수, 인터액티브하게 사용자가 한글자 입력할 때마다 바로 받으려면 cbreak 함수 호출

컬러

init_screen 호출 이후 start_color 함수 호출
color 사용 가능한지는 has_colors? 함수로 알 수 있고 사용가능한 색의수는 colors 함수로 알 수 있다.
색을 표시하려면 init_pair 함수로 pair에 글자색과 배경색을 지정한 다음 attron 함수로 색을 지정하고 출력한다.
색 자체를 RGB 조합으로 지정하려면 init_color 함수를 호출하면 될듯 (시험해보지 않음)
  init_pair(COLOR_RED,COLOR_RED,COLOR_BLACK)
  init_pair(COLOR_YELLOW, COLOR_YELLOW, COLOR_BLACK)
  setpos((lines - 5) / 2, 20)
  attron(color_pair(COLOR_RED) | A_NORMAL) {
   addstr("한글 시험")
  }
  attron(color_pair(COLOR_YELLOW) | A_BOLD) {
   addstr(" -> 굵은 글자")
  }  

예제

# encoding: UTF-8

require 'curses'
include Curses

def show_colors(line = 0)
end

init_screen
begin
  start_color  # enable color, 호출 없으면 colors 함수가 0을 반환
  crmode
  curs_set(0) # hide cursor
  str = "루비 curse 라이브러리 시험"
  0.step(colors) do |c|
    init_pair(c, c, COLOR_BLACK)
  end
  0.step(colors) do |c|  
    setpos((lines - colors) / 2 + c, (cols - str.length) / 2 - 4)
    attron(color_pair(c)) { addstr(c.to_s) }
    setpos((lines - colors) / 2 + c, (cols - str.length) / 2)
    (0...str.length).each do |i|
      attron(color_pair((c + i + 1)%16)) { addstr(str[i]) }
    end
  end  
  refresh
  getch
ensure
  close_screen
end


댓글

이 블로그의 인기 게시물

터미널에서 스칼라 파일 직접 컴파일, 실행

로잉 머신 운동 2달째